Skip to content

Personal AI, On Personal Devices

Python

fix: wire capability/rate-limit/audit enforcement into server + managed-agent paths (#827)

kire610da30b3022d6b
diff --git a/docs/user-guide/security.md b/docs/user-guide/security.md
index af8b190c..e0c0b854 100644
--- a/docs/user-guide/security.md
+++ b/docs/user-guide/security.md
@@ -60,6 +60,67 @@ The security module has four independently usable components:
---
+## Capability policies and runtime identities
+
+Capability checks restrict tool dispatch and direct agent operations. Built-in
+requirements cannot be weakened by omitting them from a tool's metadata. Remote
+MCP tools require `tool:invoke`, and third-party tools can declare additional
+requirements. Capability grants do not bypass a tool's confirmation requirement.
+
+The `shared` and `server` security profiles enable capabilities with
+`default_deny = true`. Without a policy file, their baseline grants new agents
+`file:read`, `network:fetch`, `memory:read`, and `memory:write`. Code execution,
+file writes, channel sends, scheduling, and administrative operations require
+additional grants. The personal/default profile keeps capability checks opt-in.
+
+To choose the exact grants, configure a policy file:
+
+```toml
+[security]
+profile = "shared"
+
+[security.capabilities]
+policy_path = "/absolute/path/capabilities.json"
+```
+
+Individual fields override the profile: specifying only `policy_path` preserves
+its enabled, default-deny behavior. An explicit `enabled = false` disables the
+capability check, and an explicit `default_deny = false` allows capabilities not
+otherwise denied. When capabilities are enabled, policy initialization failure
+stops startup in every profile. Shared/server profiles also stop if rate-limit
+initialization fails. Missing or malformed policy files are errors; the native
+Rust capability backend remains required.
+
+An explicit policy file receives **no automatic baseline grants**. For example,
+this policy permits reads through MCP and denies other capabilities:
+
+```json
+{
+ "agents": [
+ {"agent_id": "mcp", "grants": [{"capability": "file:read"}]}
+ ]
+}
+```
+
+`{"agents": []}` denies all capability-bearing operations when
+`default_deny = true`. The reviewed `calculator` and `think` tools require no
+capability. A `_default` entry supplies grants for identities without their own
+entry; a specific identity's policy takes precedence over `_default`.
+
+| Execution path | Policy identity |
+| --- | --- |
+| Managed-agent tick or stream | The managed agent's ID |
+| CLI, SDK, or selected server agent | The selected runtime agent name/ID |
+| Server agent-management API | `server:api` |
+| Standalone MCP executor | `mcp`, unless explicitly overridden |
+| Learning environment | `learning`, unless explicitly overridden |
+| Scheduler without a selected agent | `scheduler` |
+
+Rate-limit keys include both identity and tool name. The audit log records tool
+completion, capability denials, and rate-limit denials with that identity.
+
+---
+
## GuardrailsEngine
`GuardrailsEngine` wraps any `InferenceEngine` and scans both the input messages and the output content. It is not registered in `EngineRegistry` — you create it directly by wrapping an existing engine instance.
diff --git a/src/openjarvis/agents/_stubs.py b/src/openjarvis/agents/_stubs.py
index b456fdf0..e4b1e35f 100644
--- a/src/openjarvis/agents/_stubs.py
+++ b/src/openjarvis/agents/_stubs.py
@@ -63,6 +63,8 @@ class BaseAgent(ABC):
# function-calling loop. Specialized agents keep their own execution
# class even when process-wide MCP tools are available.
supports_managed_tool_fallback: bool = False
+ required_capabilities: tuple[str, ...] = ()
+ uses_direct_operations: bool = False
def __init__(
self,
@@ -74,12 +76,18 @@ class BaseAgent(ABC):
max_tokens: Optional[int] = None,
prompt_builder: Optional[Any] = None,
engine_options: Optional[Dict[str, Any]] = None,
+ capability_policy: Optional[Any] = None,
+ rate_limiter: Optional[Any] = None,
+ agent_id: Optional[str] = None,
) -> None:
self._engine = engine
self._model = model
self._bus = bus
self._prompt_builder = prompt_builder
self._engine_options: Dict[str, Any] = dict(engine_options or {})
+ self._capability_policy = capability_policy
+ self._rate_limiter = rate_limiter
+ self._runtime_agent_id = agent_id or getattr(self, "agent_id", "")
# Three-tier resolution: explicit arg > config > class default > hardcoded
if temperature is not None and max_tokens is not None:
@@ -114,6 +122,47 @@ class BaseAgent(ABC):
# Concrete helpers
# ------------------------------------------------------------------
+ def _execution_denied_result(
+ self,
+ required_capabilities: Optional[List[str]] = None,
+ *,
+ operation: str = "agent_run",
+ ) -> Optional[AgentResult]:
+ """Return a denial result when a direct agent operation is forbidden."""
+ required = list(
+ required_capabilities
+ if required_capabilities is not None
+ else self.required_capabilities
+ )
+ if not required:
+ return None
+ result = self._authorize_direct_operation(required, operation=operation)
+ if result.success:
+ return None
+ return AgentResult(
+ content=result.content,
+ tool_results=[result],
+ metadata={"error": True, "security_denied": True},
+ )
+
+ def _authorize_direct_operation(
+ self,
+ required_capabilities: List[str],
+ *,
+ operation: str,
+ ) -> ToolResult:
+ """Authorize a non-BaseTool operation using this runtime identity."""
+ from openjarvis.security.runtime import authorize_secured_operation
+
+ return authorize_secured_operation(
+ operation,
+ required_capabilities,
+ bus=self._bus,
+ capability_policy=self._capability_policy,
+ rate_limiter=self._rate_limiter,
+ agent_id=self._runtime_agent_id,
+ )
+
def _emit_turn_start(self, input: str) -> None:
"""Publish ``AGENT_TURN_START`` if an event bus is available."""
if self._bus:
@@ -367,6 +416,7 @@ class ToolUsingAgent(BaseAgent):
loop_guard_config: Optional[Any] = None,
capability_policy: Optional[Any] = None,
agent_id: Optional[str] = None,
+ rate_limiter: Optional[Any] = None,
interactive: bool = False,
confirm_callback: Optional[Any] = None,
skill_few_shot_examples: Optional[List[str]] = None,
@@ -379,6 +429,9 @@ class ToolUsingAgent(BaseAgent):
temperature=temperature,
max_tokens=max_tokens,
prompt_builder=prompt_builder,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_id,
)
from openjarvis.tools._stubs import ToolExecutor
@@ -394,6 +447,7 @@ class ToolUsingAgent(BaseAgent):
agent_id=_aid,
interactive=interactive,
confirm_callback=confirm_callback,
+ rate_limiter=rate_limiter,
)
# Resolve max_turns: explicit arg > config > class default > 10
if max_turns is not None:
diff --git a/src/openjarvis/agents/claude_code.py b/src/openjarvis/agents/claude_code.py
index 4b69205f..9057dc39 100644
--- a/src/openjarvis/agents/claude_code.py
+++ b/src/openjarvis/agents/claude_code.py
@@ -55,6 +55,7 @@ class ClaudeCodeAgent(BaseAgent):
agent_id = "claude_code"
accepts_tools = False
+ required_capabilities = ("code:execute", "file:read", "file:write")
_default_temperature = 0.7
_default_max_tokens = 1024
@@ -72,6 +73,9 @@ class ClaudeCodeAgent(BaseAgent):
allowed_tools: Optional[List[str]] = None,
system_prompt: str = "",
timeout: int = 300,
+ capability_policy: Optional[Any] = None,
+ rate_limiter: Optional[Any] = None,
+ agent_id: Optional[str] = None,
) -> None:
super().__init__(
engine,
@@ -79,6 +83,9 @@ class ClaudeCodeAgent(BaseAgent):
bus=bus,
temperature=temperature,
max_tokens=max_tokens,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_id,
)
self._api_key = api_key or os.environ.get("ANTHROPIC_API_KEY", "")
self._workspace = workspace or os.getcwd()
@@ -164,6 +171,9 @@ class ClaudeCodeAgent(BaseAgent):
Spawns ``node index.mjs``, writes a JSON request to stdin, and
reads sentinel-delimited JSON output from stdout.
"""
+ denied = self._execution_denied_result()
+ if denied is not None:
+ return denied
self._emit_turn_start(input)
runner_dir = self._ensure_runner()
diff --git a/src/openjarvis/agents/deep_research.py b/src/openjarvis/agents/deep_research.py
index b9632a04..6a21ea2e 100644
--- a/src/openjarvis/agents/deep_research.py
+++ b/src/openjarvis/agents/deep_research.py
@@ -189,6 +189,7 @@ class DeepResearchAgent(ToolUsingAgent):
max_tokens=max_tokens,
interactive=interactive,
confirm_callback=confirm_callback,
+ **kwargs,
)
@staticmethod
diff --git a/src/openjarvis/agents/executor.py b/src/openjarvis/agents/executor.py
index 8315b841..1c324c0d 100644
--- a/src/openjarvis/agents/executor.py
+++ b/src/openjarvis/agents/executor.py
@@ -150,10 +150,53 @@ class AgentExecutor:
from openjarvis.core.registry import AgentRegistry
agent_cls = AgentRegistry.get(agent_type)
- agent = agent_cls(
- engine=getattr(self._manager, "_engine", None),
+ engine = (
+ getattr(self._system, "engine", None)
+ if self._system is not None
+ else getattr(self._manager, "_engine", None)
+ )
+ if not tools:
+ agent = agent_cls(
+ engine=engine,
+ system_prompt=system_prompt,
+ bus=self._bus,
+ )
+ return agent.run(input_text)
+
+ # Session-expiry persistence asks a simple agent to use memory/skill
+ # tools. A SimpleAgent cannot call them, so resolve the requested tools
+ # and use the standard secured function-calling agent for this
+ # ephemeral turn instead of silently ignoring ``tools``.
+ import openjarvis.tools # noqa: F401
+ from openjarvis.agents.orchestrator import OrchestratorAgent
+ from openjarvis.core.registry import ToolRegistry
+ from openjarvis.tools._stubs import BaseTool
+
+ instances = []
+ for name in tools:
+ if not ToolRegistry.contains(name):
+ continue
+ registered = ToolRegistry.get(name)
+ if isinstance(registered, BaseTool):
+ instances.append(registered)
+ elif isinstance(registered, type) and issubclass(registered, BaseTool):
+ instances.append(registered())
+
+ execution_cls = (
+ agent_cls
+ if getattr(agent_cls, "accepts_tools", False)
+ else OrchestratorAgent
+ )
+ system = self._system
+ agent = execution_cls(
+ engine=engine,
+ model=getattr(system, "model", "") or _AGENT_TICK_DEFAULT_MODEL,
system_prompt=system_prompt,
+ tools=instances,
bus=self._bus,
+ capability_policy=getattr(system, "capability_policy", None),
+ rate_limiter=getattr(system, "rate_limiter", None),
+ agent_id=f"ephemeral:{agent_type}",
)
return agent.run(input_text)
@@ -458,6 +501,19 @@ class AgentExecutor:
# actively invoking web_search/memory_*/etc.
if self._bus is not None:
agent_kwargs["bus"] = self._bus
+ # Wire RBAC/rate-limiting from the system's SecurityContext into the
+ # agent's own ToolExecutor. Without this, every managed-agent tick
+ # went through ToolUsingAgent's default capability_policy=None /
+ # rate_limiter=None, so tool calls were never actually gated even
+ # when the config had capabilities/rate-limiting enabled.
+ if self._system is not None:
+ cap_policy = getattr(self._system, "capability_policy", None)
+ if cap_policy is not None:
+ agent_kwargs["capability_policy"] = cap_policy
+ rate_limiter = getattr(self._system, "rate_limiter", None)
+ if rate_limiter is not None:
+ agent_kwargs["rate_limiter"] = rate_limiter
+ agent_kwargs["agent_id"] = agent["id"]
# Propagate confirmation policy from the AgentExecutor down to the
# agent's own ToolExecutor. Set by CLI paths like `jarvis agents ask`
# so non-interactive runs can auto-approve tool execution.
@@ -550,14 +606,18 @@ class AgentExecutor:
if resolved_toolkit.mcp_clients:
agent_instance._mcp_clients = resolved_toolkit.mcp_clients
- # Inject the managed-agent UUID into the agent's ToolExecutor so
- # emitted TOOL_CALL_START/END events carry it; the trace subscriber
- # below filters by ``event.data["agent"] == agent_id`` and would
- # otherwise drop every tool call (the class-level agent_id like
- # "monitor_operative" doesn't match the runtime UUID).
- inner_executor = getattr(agent_instance, "_executor", None)
- if inner_executor is not None and hasattr(inner_executor, "_agent_id"):
- inner_executor._agent_id = agent["id"]
+ # Re-apply runtime security after constructor fallbacks and inject the
+ # managed UUID into both direct-operation agents and ToolExecutors.
+ # The trace subscriber also relies on this identity.
+ from openjarvis.security.runtime import wire_agent_security
+
+ wire_agent_security(
+ agent_instance,
+ bus=self._bus,
+ capability_policy=getattr(self._system, "capability_policy", None),
+ rate_limiter=getattr(self._system, "rate_limiter", None),
+ agent_id=agent["id"],
+ )
logger.info(
"Agent %s: tool wiring — %d tools resolved (%s), agent class %s",
diff --git a/src/openjarvis/agents/hybrid/_base.py b/src/openjarvis/agents/hybrid/_base.py
index 97f315ae..7d701268 100644
--- a/src/openjarvis/agents/hybrid/_base.py
+++ b/src/openjarvis/agents/hybrid/_base.py
@@ -403,6 +403,9 @@ class LocalCloudAgent(BaseAgent):
"""
accepts_tools: bool = False
+ # Hybrid agents directly invoke web-search and, in SWE mode, generated
+ # shell commands without owning a ToolExecutor.
+ uses_direct_operations: bool = True
def __init__(
self,
@@ -416,6 +419,9 @@ class LocalCloudAgent(BaseAgent):
bus: Optional[Any] = None,
temperature: Optional[float] = None,
max_tokens: Optional[int] = None,
+ capability_policy: Optional[Any] = None,
+ rate_limiter: Optional[Any] = None,
+ agent_id: Optional[str] = None,
) -> None:
super().__init__(
engine,
@@ -423,6 +429,9 @@ class LocalCloudAgent(BaseAgent):
bus=bus,
temperature=temperature,
max_tokens=max_tokens,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_id,
)
self._cloud_model = model
self._cloud_endpoint = (cloud_endpoint or "anthropic").lower()
@@ -1278,12 +1287,53 @@ class LocalCloudAgent(BaseAgent):
# Run contract
# ------------------------------------------------------------------
+ def _required_capabilities_for_run(
+ self,
+ context: Optional[AgentContext],
+ ) -> List[str]:
+ """Derive capabilities from direct operations reachable this run.
+
+ Subclasses with worker pools may extend this hook based on the
+ concrete worker/action types they expose, rather than relying only on
+ generic configuration flags.
+ """
+ required = list(self.required_capabilities)
+ task_meta = context.metadata.get("task", {}) if context is not None else {}
+ if not isinstance(task_meta, dict):
+ task_meta = {}
+ swe_mode = (
+ bool(self._cfg.get("swe_use_agent_loop"))
+ and bool(task_meta.get("problem_statement"))
+ and bool(task_meta.get("repo"))
+ and bool(task_meta.get("base_commit"))
+ )
+ if bool(self._cfg.get("swe_use_agent_loop")) or bool(
+ task_meta.get("repo") and task_meta.get("base_commit")
+ ):
+ required.extend(("code:execute", "file:read", "file:write"))
+ if str(self._cfg.get("search_backend", "provider")).lower() == "tavily":
+ required.append("network:fetch")
+ web_search_enabled, _ = web_search_cfg(self._cfg)
+ if web_search_enabled and not swe_mode:
+ # Provider-hosted search is still an external fetch even when
+ # ``search_backend`` remains at its default value.
+ required.append("network:fetch")
+ if self._cfg.get("retriever_url"):
+ required.append("network:fetch")
+ return list(dict.fromkeys(required))
+
def run(
self,
input: str,
context: Optional[AgentContext] = None,
**kwargs: Any,
) -> AgentResult:
+ denied = self._execution_denied_result(
+ self._required_capabilities_for_run(context),
+ operation="hybrid_agent_run",
+ )
+ if denied is not None:
+ return denied
self._emit_turn_start(input)
t0 = time.time()
events = _open_trace()
diff --git a/src/openjarvis/agents/hybrid/advisors.py b/src/openjarvis/agents/hybrid/advisors.py
index b6cec027..6337561f 100644
--- a/src/openjarvis/agents/hybrid/advisors.py
+++ b/src/openjarvis/agents/hybrid/advisors.py
@@ -279,7 +279,20 @@ class AdvisorsAgent(LocalCloudAgent):
``"tavily"``. Returns ``(text, p_tok, c_tok, n_searches, turns,
search_cost_usd)``.
"""
- if str(self._cfg.get("search_backend", "provider")).lower() == "tavily":
+ search_backend = str(self._cfg.get("search_backend", "provider")).lower()
+ operation = (
+ "advisors_tavily"
+ if search_backend == "tavily"
+ else "advisors_provider_search"
+ )
+ authorization = self._authorize_direct_operation(
+ ["network:fetch"],
+ operation=operation,
+ )
+ if not authorization.success:
+ return authorization.content, 0, 0, 0, 1, 0.0
+
+ if search_backend == "tavily":
res = tavily_search_context(
query or user,
max_results=int(self._cfg.get("tavily_max_results", 5)),
diff --git a/src/openjarvis/agents/hybrid/conductor.py b/src/openjarvis/agents/hybrid/conductor.py
index 2ff06d85..91d63001 100644
--- a/src/openjarvis/agents/hybrid/conductor.py
+++ b/src/openjarvis/agents/hybrid/conductor.py
@@ -769,6 +769,42 @@ class ConductorAgent(LocalCloudAgent):
self._cloud_model,
)
+ def _call_worker_secured(
+ self,
+ worker: Dict[str, Any],
+ prompt: str,
+ cfg: Dict[str, Any],
+ *,
+ web_search_tool: Optional[Dict[str, Any]] = None,
+ web_search_max_uses: int = 8,
+ ) -> Tuple[str, int, int, bool, int, float]:
+ """Gate the selected worker immediately before external search."""
+ if web_search_tool is not None:
+ search_backend = str(cfg.get("search_backend", "provider")).lower()
+ worker_endpoint = str(worker.get("endpoint") or "openai").lower()
+ search_dispatches = search_backend == "tavily" or (
+ worker_endpoint in _SEARCH_CAPABLE_WORKER_ENDPOINTS
+ )
+ if search_dispatches:
+ operation = (
+ "conductor_tavily"
+ if search_backend == "tavily"
+ else "conductor_provider_search"
+ )
+ authorization = self._authorize_direct_operation(
+ ["network:fetch"],
+ operation=operation,
+ )
+ if not authorization.success:
+ return authorization.content, 0, 0, False, 0, 0.0
+ return _call_worker(
+ worker,
+ prompt,
+ cfg,
+ web_search_tool=web_search_tool,
+ web_search_max_uses=web_search_max_uses,
+ )
+
def _run_paradigm(
self,
input: str,
@@ -995,7 +1031,7 @@ class ConductorAgent(LocalCloudAgent):
tool_calls += bash_turns
else:
(text, w_in, w_out, is_local, n_searches, extra_cost) = (
- _call_worker(
+ self._call_worker_secured(
worker,
prompt,
cfg,
diff --git a/src/openjarvis/agents/hybrid/mini_swe_agent.py b/src/openjarvis/agents/hybrid/mini_swe_agent.py
index e4023e02..f92c5be2 100644
--- a/src/openjarvis/agents/hybrid/mini_swe_agent.py
+++ b/src/openjarvis/agents/hybrid/mini_swe_agent.py
@@ -1552,6 +1552,7 @@ class MiniSWEAgent(LocalCloudAgent):
"""
agent_id = "mini_swe_agent"
+ required_capabilities = ("code:execute", "file:read", "file:write")
def _run_paradigm(
self,
diff --git a/src/openjarvis/agents/hybrid/minions.py b/src/openjarvis/agents/hybrid/minions.py
index 8c60866c..7c5f4ff5 100644
--- a/src/openjarvis/agents/hybrid/minions.py
+++ b/src/openjarvis/agents/hybrid/minions.py
@@ -452,6 +452,67 @@ class MinionsAgent(LocalCloudAgent):
agent_id = "minions"
+ def _required_capabilities_for_run(
+ self,
+ context: Optional[AgentContext],
+ ) -> List[str]:
+ """Include the legacy-default GAIA prefetch when it is reachable."""
+ required = super()._required_capabilities_for_run(context)
+ task_meta = context.metadata.get("task", {}) if context is not None else {}
+ if not isinstance(task_meta, dict):
+ task_meta = {}
+ swe_mode = (
+ bool(self._cfg.get("swe_use_agent_loop"))
+ and bool(task_meta.get("problem_statement"))
+ and bool(task_meta.get("repo"))
+ and bool(task_meta.get("base_commit"))
+ )
+ ws_block = (
+ self._cfg.get("web_search")
+ if isinstance(self._cfg.get("web_search"), dict)
+ else None
+ )
+ ws_enabled, _ = web_search_cfg(self._cfg)
+ prefetch_on = ws_block is None or ws_enabled
+ if not swe_mode and task_meta.get("question") and prefetch_on:
+ required.append("network:fetch")
+ return list(dict.fromkeys(required))
+
+ def _prefetch_context_secured(
+ self,
+ question: str,
+ *,
+ max_uses: int,
+ search_backend: str,
+ tavily_max_results: int,
+ ) -> Dict[str, Any]:
+ """Gate the GAIA prefetch immediately before provider/Tavily I/O."""
+ operation = (
+ "minions_tavily"
+ if search_backend == "tavily"
+ else "minions_provider_prefetch"
+ )
+ authorization = self._authorize_direct_operation(
+ ["network:fetch"],
+ operation=operation,
+ )
+ if not authorization.success:
+ return {
+ "text": "",
+ "tokens": 0,
+ "cost_usd": 0.0,
+ "n_searches": 0,
+ "error": authorization.content,
+ }
+ return _prefetch_context(
+ question,
+ self._cloud_endpoint,
+ self._cloud_model,
+ max_uses=max_uses,
+ search_backend=search_backend,
+ tavily_max_results=tavily_max_results,
+ )
+
def _is_soft_failure(self, exc: BaseException) -> Optional[str]:
# Known soft-failure modes: Qwen worker JSON malformed, Anthropic
# 400/529, KeyError on missing schema fields.
@@ -589,10 +650,8 @@ class MinionsAgent(LocalCloudAgent):
or ws_enabled
)
if task_meta.get("question") and prefetch_on:
- prefetch = _prefetch_context(
+ prefetch = self._prefetch_context_secured(
task_meta["question"],
- self._cloud_endpoint,
- self._cloud_model,
max_uses=ws_max_uses,
search_backend=str(cfg.get("search_backend", "provider")).lower(),
tavily_max_results=int(cfg.get("tavily_max_results", 5)),
diff --git a/src/openjarvis/agents/hybrid/skillorchestra.py b/src/openjarvis/agents/hybrid/skillorchestra.py
index a5b029eb..6463681a 100644
--- a/src/openjarvis/agents/hybrid/skillorchestra.py
+++ b/src/openjarvis/agents/hybrid/skillorchestra.py
@@ -204,6 +204,24 @@ class SkillOrchestraAgent(LocalCloudAgent):
"""Inference-time skill-aware router. See module docstring."""
agent_id = "skillorchestra"
+ required_capabilities = ("code:execute", "file:read", "file:write")
+
+ def _required_capabilities_for_run(
+ self,
+ context: Optional[AgentContext],
+ ) -> List[str]:
+ """Include provider search for the QA tool set exposed this run."""
+ required = super()._required_capabilities_for_run(context)
+ task_meta = (context.metadata.get("task") if context is not None else {}) or {}
+ swe_mode = (
+ bool(self._cfg.get("swe_use_agent_loop"))
+ and bool(task_meta.get("problem_statement"))
+ and bool(task_meta.get("repo"))
+ and bool(task_meta.get("base_commit"))
+ )
+ if not swe_mode:
+ required.append("network:fetch")
+ return list(dict.fromkeys(required))
def _route_call(
self,
diff --git a/src/openjarvis/agents/hybrid/skillorchestra/agent.py b/src/openjarvis/agents/hybrid/skillorchestra/agent.py
index 97409268..ccc501e5 100644
--- a/src/openjarvis/agents/hybrid/skillorchestra/agent.py
+++ b/src/openjarvis/agents/hybrid/skillorchestra/agent.py
@@ -30,7 +30,7 @@ from __future__ import annotations
import json
from pathlib import Path
-from typing import Any, Dict, Optional, Tuple
+from typing import Any, Dict, List, Optional, Tuple
from openjarvis.agents._stubs import AgentContext
from openjarvis.core.registry import AgentRegistry
@@ -55,6 +55,31 @@ class SkillOrchestraAgent(LocalCloudAgent):
"""Inference-time skill-aware orchestrator. See module docstring."""
agent_id = "skillorchestra"
+ # The QA orchestrator always exposes enhance_reasoning, which executes
+ # generated Python when selected. Gate the agent before its first model
+ # turn as well as immediately before the subprocess in tools.run_code.
+ required_capabilities = ("code:execute", "file:read", "file:write")
+
+ # ------------------------------------------------------------------
+
+ def _required_capabilities_for_run(
+ self,
+ context: Optional[AgentContext],
+ ) -> List[str]:
+ """Include search access for the QA tool set exposed this run."""
+ required = super()._required_capabilities_for_run(context)
+ task_meta = (context.metadata.get("task") if context is not None else {}) or {}
+ swe_mode = (
+ bool(self._cfg.get("swe_use_agent_loop"))
+ and bool(task_meta.get("problem_statement"))
+ and bool(task_meta.get("repo"))
+ and bool(task_meta.get("base_commit"))
+ )
+ if not swe_mode:
+ # The QA orchestrator always exposes search. Provider-hosted
+ # search is the default even with no retriever/search flags.
+ required.append("network:fetch")
+ return list(dict.fromkeys(required))
# ------------------------------------------------------------------
diff --git a/src/openjarvis/agents/hybrid/skillorchestra/tools.py b/src/openjarvis/agents/hybrid/skillorchestra/tools.py
index 4cc8ce11..d6b4cc3b 100644
--- a/src/openjarvis/agents/hybrid/skillorchestra/tools.py
+++ b/src/openjarvis/agents/hybrid/skillorchestra/tools.py
@@ -161,6 +161,24 @@ def run_code(
timeout=60)`` verbatim. Execution failures yield empty ``exec_result``
rather than raising — the orchestrator learns the model can't code.
"""
+ authorization = agent._authorize_direct_operation(
+ ["code:execute", "file:read", "file:write"],
+ operation="skillorchestra_code",
+ )
+ if not authorization.success:
+ return {
+ "tool": "enhance_reasoning",
+ "model": spec.model,
+ "alias": spec.alias,
+ "generated_code": "",
+ "exec_result": authorization.content,
+ "response": authorization.content,
+ "tokens_in": 0,
+ "tokens_out": 0,
+ "cost_usd": 0.0,
+ "is_local": spec.is_local,
+ }
+
prompt = (
context_str.strip()
+ "\n\n"
@@ -339,6 +357,19 @@ def run_search(
search_uses = 0
if search_backend == "tavily":
+ search_operation = "skillorchestra_tavily"
+ elif retriever_url:
+ search_operation = "skillorchestra_retriever"
+ else:
+ search_operation = "skillorchestra_provider_search"
+ authorization = agent._authorize_direct_operation(
+ ["network:fetch"],
+ operation=search_operation,
+ )
+
+ if not authorization.success:
+ contents.append(f"[search blocked: {authorization.content}]")
+ elif search_backend == "tavily":
res = tavily_search_context(query, max_results=tavily_max_results)
contents.append(res["text"])
search_uses = int(res["n_searches"])
diff --git a/src/openjarvis/agents/hybrid/toolorchestra.py b/src/openjarvis/agents/hybrid/toolorchestra.py
index fdb6ebb1..4c6dca7a 100644
--- a/src/openjarvis/agents/hybrid/toolorchestra.py
+++ b/src/openjarvis/agents/hybrid/toolorchestra.py
@@ -1143,6 +1143,78 @@ class ToolOrchestraAgent(LocalCloudAgent):
f"got {mode!r}"
)
+ @staticmethod
+ def _worker_required_capabilities(
+ worker: Dict[str, Any],
+ *,
+ swe_mode: bool = False,
+ ) -> List[str]:
+ """Return direct-operation capabilities for one concrete dispatch."""
+ worker_type = str(worker.get("type", worker.get("endpoint", "openai"))).lower()
+ if worker_type in _TOOLORCH_SEARCH_TYPES:
+ return ["network:fetch"]
+ if swe_mode:
+ return ["code:execute", "file:read", "file:write"]
+ if worker_type == "modal-python":
+ return ["code:execute"]
+ return []
+
+ def _call_worker_secured(
+ self,
+ worker: Dict[str, Any],
+ prompt: str,
+ cfg: Dict[str, Any],
+ ) -> Tuple[str, int, int, bool, float, int]:
+ """Gate the selected worker immediately before its direct action."""
+ required = self._worker_required_capabilities(worker)
+ if required:
+ authorization = self._authorize_direct_operation(
+ required,
+ operation="toolorchestra_worker",
+ )
+ if not authorization.success:
+ return authorization.content, 0, 0, False, 0.0, 0
+ return _call_worker(worker, prompt, cfg)
+
+ def _swe_call_worker_secured(
+ self,
+ worker: Dict[str, Any],
+ prompt: str,
+ cfg: Dict[str, Any],
+ task: Dict[str, Any],
+ workdir: Path,
+ turn: int,
+ ) -> Tuple[str, int, int, bool, float, int, int]:
+ """Gate a selected SWE/search worker immediately before dispatch."""
+ worker_type = str(worker.get("type", "openai")).lower()
+ required = self._worker_required_capabilities(
+ worker,
+ swe_mode=worker_type not in _TOOLORCH_SEARCH_TYPES,
+ )
+ if required:
+ authorization = self._authorize_direct_operation(
+ required,
+ operation="toolorchestra_swe_worker",
+ )
+ if not authorization.success:
+ return authorization.content, 0, 0, False, 0.0, 0, 0
+ return _swe_call_worker(worker, prompt, cfg, task, workdir, turn)
+
+ def _call_modal_python_secured(
+ self,
+ code: str,
+ *,
+ timeout_s: int,
+ ) -> Tuple[str, int]:
+ """Gate generated Python immediately before sandbox execution."""
+ authorization = self._authorize_direct_operation(
+ ["code:execute"],
+ operation="toolorchestra_modal_python",
+ )
+ if not authorization.success:
+ return authorization.content, -1
+ return _call_modal_python(code, timeout_s=timeout_s)
+
def _run_paradigm(
self,
input: str,
@@ -1154,6 +1226,47 @@ class ToolOrchestraAgent(LocalCloudAgent):
return self._run_rl(input, context, **kwargs)
return self._run_prompted(input, context, **kwargs)
+ def _required_capabilities_for_run(
+ self,
+ context: Optional[AgentContext],
+ ) -> List[str]:
+ """Cover the concrete workers/actions exposed by this run.
+
+ ToolOrchestra's default pool contains a hosted-search worker even
+ when ``search_backend`` is not ``tavily``. RL paper mode additionally
+ exposes Tavily and generated Python in Modal. Deriving from those
+ actual action types keeps the gate aligned with dispatch behavior.
+ """
+ required = super()._required_capabilities_for_run(context)
+ mode = str(self._cfg.get("orchestrator_mode", "prompted")).lower()
+ if mode == "rl":
+ # Both the default expert mapping and the paper mapping expose a
+ # search action; paper mode also executes generated Python.
+ required.append("network:fetch")
+ if str(self._cfg.get("pool", "")).lower() == "paper":
+ required.append("code:execute")
+ return list(dict.fromkeys(required))
+
+ workers = self._cfg.get("workers")
+ if not workers:
+ workers = _resolve_worker_pool(
+ self._cfg,
+ self._local_model,
+ self._local_endpoint,
+ self._cloud_model,
+ self._cloud_endpoint,
+ )
+ worker_types = {
+ str(worker.get("type", worker.get("endpoint", "openai"))).lower()
+ for worker in workers
+ if isinstance(worker, dict)
+ }
+ if worker_types.intersection(_TOOLORCH_SEARCH_TYPES):
+ required.append("network:fetch")
+ if "modal-python" in worker_types:
+ required.append("code:execute")
+ return list(dict.fromkeys(required))
+
# ------------------------------------------------------------------
# Legacy prompted-orchestrator path.
# ------------------------------------------------------------------
@@ -1297,7 +1410,7 @@ class ToolOrchestraAgent(LocalCloudAgent):
extra_cost,
n_searches,
bash_turns,
- ) = _swe_call_worker(
+ ) = self._swe_call_worker_secured(
worker,
str(w_input),
cfg,
@@ -1308,7 +1421,7 @@ class ToolOrchestraAgent(LocalCloudAgent):
tool_calls += bash_turns
else:
w_text, w_in, w_out, is_local, extra_cost, n_searches = (
- _call_worker(worker, str(w_input), cfg)
+ self._call_worker_secured(worker, str(w_input), cfg)
)
if is_local:
tokens_local += w_in + w_out
@@ -1349,7 +1462,7 @@ class ToolOrchestraAgent(LocalCloudAgent):
)
if swe_mode and shared_workdir is not None:
(ans, w_in, w_out, is_local, extra_cost, _, bash_turns) = (
- _swe_call_worker(
+ self._swe_call_worker_secured(
worker,
question,
cfg,
@@ -1360,8 +1473,8 @@ class ToolOrchestraAgent(LocalCloudAgent):
)
tool_calls += bash_turns
else:
- ans, w_in, w_out, is_local, extra_cost, _ = _call_worker(
- worker, question, cfg
+ ans, w_in, w_out, is_local, extra_cost, _ = (
+ self._call_worker_secured(worker, question, cfg)
)
if is_local:
tokens_local += w_in + w_out
@@ -1695,7 +1808,7 @@ class ToolOrchestraAgent(LocalCloudAgent):
extra_cost,
n_searches,
bash_turns,
- ) = _swe_call_worker(
+ ) = self._swe_call_worker_secured(
worker,
w_input,
cfg,
@@ -1705,7 +1818,7 @@ class ToolOrchestraAgent(LocalCloudAgent):
)
else:
w_text, w_in, w_out, is_local, extra_cost, n_searches = (
- _call_worker(worker, w_input, cfg)
+ self._call_worker_secured(worker, w_input, cfg)
)
if is_local:
tokens_local += w_in + w_out
@@ -1728,9 +1841,11 @@ class ToolOrchestraAgent(LocalCloudAgent):
code = _extract_first_python_block(w_text)
if code:
timeout_s = int(cfg.get("modal_python_timeout_s", 60))
- modal_exec_output, modal_exec_rc = _call_modal_python(
- code,
- timeout_s=timeout_s,
+ modal_exec_output, modal_exec_rc = (
+ self._call_modal_python_secured(
+ code,
+ timeout_s=timeout_s,
+ )
)
tool_calls += 1
w_text = (
@@ -1786,7 +1901,7 @@ class ToolOrchestraAgent(LocalCloudAgent):
fb_bash_turns = 0
if swe_mode and shared_workdir is not None:
(ans, w_in, w_out, is_local, extra_cost, _, fb_bash_turns) = (
- _swe_call_worker(
+ self._swe_call_worker_secured(
worker,
question,
cfg,
@@ -1797,8 +1912,8 @@ class ToolOrchestraAgent(LocalCloudAgent):
)
tool_calls += fb_bash_turns
else:
- ans, w_in, w_out, is_local, extra_cost, _ = _call_worker(
- worker, question, cfg
+ ans, w_in, w_out, is_local, extra_cost, _ = (
+ self._call_worker_secured(worker, question, cfg)
)
if is_local:
tokens_local += w_in + w_out
diff --git a/src/openjarvis/agents/monitor_operative.py b/src/openjarvis/agents/monitor_operative.py
index 9113c7e8..708264ee 100644
--- a/src/openjarvis/agents/monitor_operative.py
+++ b/src/openjarvis/agents/monitor_operative.py
@@ -141,6 +141,7 @@ class MonitorOperativeAgent(ToolUsingAgent):
interactive=interactive,
confirm_callback=confirm_callback,
prompt_builder=prompt_builder,
+ **kwargs,
)
# Validate strategies
if memory_extraction not in VALID_MEMORY_EXTRACTION:
diff --git a/src/openjarvis/agents/native_openhands.py b/src/openjarvis/agents/native_openhands.py
index 5358fa3a..7f4006bd 100644
--- a/src/openjarvis/agents/native_openhands.py
+++ b/src/openjarvis/agents/native_openhands.py
@@ -75,6 +75,9 @@ class NativeOpenHandsAgent(ToolUsingAgent):
max_tokens: Optional[int] = None,
interactive: bool = False,
confirm_callback=None,
+ capability_policy: Optional[Any] = None,
+ agent_id: Optional[str] = None,
+ rate_limiter: Optional[Any] = None,
) -> None:
super().__init__(
engine,
@@ -86,10 +89,12 @@ class NativeOpenHandsAgent(ToolUsingAgent):
max_tokens=max_tokens,
interactive=interactive,
confirm_callback=confirm_callback,
+ capability_policy=capability_policy,
+ agent_id=agent_id,
+ rate_limiter=rate_limiter,
)
- @staticmethod
- def _expand_urls(text: str) -> tuple[str, bool]:
+ def _expand_urls(self, text: str) -> tuple[str, bool]:
"""If the user message contains a URL, fetch it and inline the content.
Returns (possibly_expanded_text, was_expanded).
@@ -101,9 +106,21 @@ class NativeOpenHandsAgent(ToolUsingAgent):
return text, False
url = url_match.group(0).rstrip(".,;)")
try:
+ from openjarvis.security.runtime import execute_secured_tool
from openjarvis.tools.web_search import WebSearchTool
- content = WebSearchTool._fetch_url(url, max_chars=4000)
+ executor = self._executor
+ result = execute_secured_tool(
+ WebSearchTool(),
+ {"query": url},
+ bus=getattr(executor, "_bus", None),
+ capability_policy=getattr(executor, "_capability_policy", None),
+ rate_limiter=getattr(executor, "_rate_limiter", None),
+ agent_id=getattr(executor, "_agent_id", self.agent_id),
+ )
+ if not result.success:
+ return text, False
+ content = result.content[:4000]
header = f"\n\n--- Content from {url} ---\n"
footer = "\n--- End of content ---\n"
expanded = text.replace(url, f"{header}{content}{footer}")
diff --git a/src/openjarvis/agents/native_react.py b/src/openjarvis/agents/native_react.py
index 6ee87a36..d04c2b8e 100644
--- a/src/openjarvis/agents/native_react.py
+++ b/src/openjarvis/agents/native_react.py
@@ -150,6 +150,9 @@ class NativeReActAgent(ToolUsingAgent):
interactive: bool = False,
confirm_callback=None,
skill_few_shot_examples: Optional[List[str]] = None,
+ capability_policy: Optional[Any] = None,
+ agent_id: Optional[str] = None,
+ rate_limiter: Optional[Any] = None,
) -> None:
super().__init__(
engine,
@@ -162,6 +165,9 @@ class NativeReActAgent(ToolUsingAgent):
interactive=interactive,
confirm_callback=confirm_callback,
skill_few_shot_examples=skill_few_shot_examples,
+ capability_policy=capability_policy,
+ agent_id=agent_id,
+ rate_limiter=rate_limiter,
)
def _parse_response(self, text: str) -> dict:
diff --git a/src/openjarvis/agents/opencode.py b/src/openjarvis/agents/opencode.py
index eab9a5a8..e08d6330 100644
--- a/src/openjarvis/agents/opencode.py
+++ b/src/openjarvis/agents/opencode.py
@@ -113,6 +113,7 @@ class OpenCodeAgent(BaseAgent):
agent_id = "opencode"
accepts_tools = False
+ required_capabilities = ("code:execute", "file:read", "file:write")
_default_temperature = 0.7
_default_max_tokens = 1024
@@ -136,6 +137,9 @@ class OpenCodeAgent(BaseAgent):
server_password: str = "",
timeout: int = 600,
opencode_bin: str = "",
+ capability_policy: Optional[Any] = None,
+ rate_limiter: Optional[Any] = None,
+ agent_id: Optional[str] = None,
) -> None:
super().__init__(
engine,
@@ -143,6 +147,9 @@ class OpenCodeAgent(BaseAgent):
bus=bus,
temperature=temperature,
max_tokens=max_tokens,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_id,
)
self._workspace = workspace or os.getcwd()
self._agent = agent
@@ -301,6 +308,9 @@ class OpenCodeAgent(BaseAgent):
**kwargs: Any,
) -> AgentResult:
"""Run a coding task through opencode and return the assistant result."""
+ denied = self._execution_denied_result()
+ if denied is not None:
+ return denied
self._emit_turn_start(input)
# Resolve which opencode provider/model to address. Fail clearly rather
diff --git a/src/openjarvis/agents/openhands.py b/src/openjarvis/agents/openhands.py
index 4432b655..b824d629 100644
--- a/src/openjarvis/agents/openhands.py
+++ b/src/openjarvis/agents/openhands.py
@@ -25,6 +25,7 @@ class OpenHandsAgent(BaseAgent):
"""
agent_id = "openhands"
+ required_capabilities = ("code:execute", "file:read", "file:write")
_default_temperature = 0.7
_default_max_tokens = 1024
@@ -38,6 +39,9 @@ class OpenHandsAgent(BaseAgent):
max_tokens: Optional[int] = None,
workspace: Optional[str] = None,
api_key: Optional[str] = None,
+ capability_policy: Optional[Any] = None,
+ rate_limiter: Optional[Any] = None,
+ agent_id: Optional[str] = None,
) -> None:
super().__init__(
engine,
@@ -45,6 +49,9 @@ class OpenHandsAgent(BaseAgent):
bus=bus,
temperature=temperature,
max_tokens=max_tokens,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_id,
)
self._workspace = workspace or os.getcwd()
self._api_key = api_key or os.environ.get("LLM_API_KEY", "")
@@ -55,6 +62,9 @@ class OpenHandsAgent(BaseAgent):
context: Optional[AgentContext] = None,
**kwargs: Any,
) -> AgentResult:
+ denied = self._execution_denied_result()
+ if denied is not None:
+ return denied
try:
from openhands.sdk import ( # type: ignore[import-untyped]
LLM,
diff --git a/src/openjarvis/agents/operative.py b/src/openjarvis/agents/operative.py
index c16163dc..46be610c 100644
--- a/src/openjarvis/agents/operative.py
+++ b/src/openjarvis/agents/operative.py
@@ -72,6 +72,7 @@ class OperativeAgent(ToolUsingAgent):
interactive=interactive,
confirm_callback=confirm_callback,
prompt_builder=prompt_builder,
+ **kwargs,
)
self._system_prompt = system_prompt or ""
self._operator_id = operator_id
diff --git a/src/openjarvis/agents/orchestrator.py b/src/openjarvis/agents/orchestrator.py
index 9d1e5744..ae5ab9a9 100644
--- a/src/openjarvis/agents/orchestrator.py
+++ b/src/openjarvis/agents/orchestrator.py
@@ -66,6 +66,8 @@ class OrchestratorAgent(ToolUsingAgent):
interactive: bool = False,
confirm_callback=None,
capability_policy: Optional[Any] = None,
+ agent_id: Optional[str] = None,
+ rate_limiter: Optional[Any] = None,
before_tool_call: Optional[Callable[[str, dict[str, Any]], bool]] = None,
) -> None:
super().__init__(
@@ -78,8 +80,10 @@ class OrchestratorAgent(ToolUsingAgent):
max_tokens=max_tokens,
interactive=interactive,
confirm_callback=confirm_callback,
- capability_policy=capability_policy,
prompt_builder=prompt_builder,
+ capability_policy=capability_policy,
+ agent_id=agent_id,
+ rate_limiter=rate_limiter,
)
self._mode = mode
self._system_prompt = system_prompt
diff --git a/src/openjarvis/agents/rlm.py b/src/openjarvis/agents/rlm.py
index c7bc8fa6..de801658 100644
--- a/src/openjarvis/agents/rlm.py
+++ b/src/openjarvis/agents/rlm.py
@@ -22,7 +22,12 @@ from openjarvis.core.events import EventBus
from openjarvis.core.registry import AgentRegistry
from openjarvis.core.types import Message, Role, ToolCall, ToolResult
from openjarvis.engine._stubs import InferenceEngine
-from openjarvis.tools._stubs import BaseTool, build_tool_descriptions
+from openjarvis.tools._stubs import (
+ BaseTool,
+ ToolExecutor,
+ ToolSpec,
+ build_tool_descriptions,
+)
# ---------------------------------------------------------------------------
# System prompt
@@ -91,6 +96,40 @@ RLM_SYSTEM_PROMPT = (
# ---------------------------------------------------------------------------
+class _RLMReplTool(BaseTool):
+ """Expose one RLM REPL instance through the canonical security executor."""
+
+ tool_id = "rlm_repl"
+
+ def __init__(self, repl: RLMRepl) -> None:
+ self._repl = repl
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name=self.tool_id,
+ description="Execute generated Python in the RLM sandbox.",
+ parameters={
+ "type": "object",
+ "properties": {"code": {"type": "string"}},
+ "required": ["code"],
+ },
+ required_capabilities=["code:execute"],
+ timeout_seconds=60.0,
+ )
+
+ def execute(self, **params: Any) -> ToolResult:
+ output = self._repl.execute(str(params.get("code", "")))
+ return ToolResult(
+ tool_name=self.tool_id,
+ content=output or "(no output)",
+ success=(
+ not output.startswith("Error:")
+ and not output.startswith("SyntaxError:")
+ ),
+ )
+
+
@AgentRegistry.register("rlm")
class RLMAgent(ToolUsingAgent):
"""Recursive Language Model agent using a persistent REPL.
@@ -106,6 +145,7 @@ class RLMAgent(ToolUsingAgent):
_default_temperature = 0.7
_default_max_tokens = 2048
_default_max_turns = 10
+ required_capabilities = ("code:execute",)
def __init__(
self,
@@ -124,6 +164,9 @@ class RLMAgent(ToolUsingAgent):
system_prompt: Optional[str] = None,
interactive: bool = False,
confirm_callback=None,
+ capability_policy: Optional[Any] = None,
+ agent_id: Optional[str] = None,
+ rate_limiter: Optional[Any] = None,
) -> None:
super().__init__(
engine,
@@ -135,7 +178,14 @@ class RLMAgent(ToolUsingAgent):
max_tokens=max_tokens,
interactive=interactive,
confirm_callback=confirm_callback,
+ capability_policy=capability_policy,
+ agent_id=agent_id,
+ rate_limiter=rate_limiter,
)
+ self._runtime_bus = bus
+ self._runtime_capability_policy = capability_policy
+ self._runtime_rate_limiter = rate_limiter
+ self._runtime_agent_id = agent_id or self.agent_id
# Override executor: RLM only creates one if tools are provided
if not self._tools:
self._executor = None # type: ignore[assignment]
@@ -155,6 +205,9 @@ class RLMAgent(ToolUsingAgent):
context: Optional[AgentContext] = None,
**kwargs: Any,
) -> AgentResult:
+ denied = self._execution_denied_result()
+ if denied is not None:
+ return denied
self._emit_turn_start(input)
# Build system prompt with tool section
@@ -190,6 +243,13 @@ class RLMAgent(ToolUsingAgent):
tool_arg_names=self._tool_arg_names(),
max_output_chars=self._max_output_chars,
)
+ repl_executor = ToolExecutor(
+ [_RLMReplTool(repl)],
+ bus=self._runtime_bus,
+ capability_policy=self._runtime_capability_policy,
+ rate_limiter=self._runtime_rate_limiter,
+ agent_id=self._runtime_agent_id,
+ )
# Resolve context and inject into REPL
ctx_text = self._resolve_context(context)
@@ -246,22 +306,21 @@ class RLMAgent(ToolUsingAgent):
)
# Execute code in REPL
- output = repl.execute(code)
+ repl_result = repl_executor.execute(
+ ToolCall(
+ id=f"rlm-repl-{turns}",
+ name="rlm_repl",
+ arguments=json.dumps({"code": code}),
+ )
+ )
+ output = repl_result.content
if self._repl_tool_results:
all_tool_results.extend(self._repl_tool_results)
self._repl_tool_results = []
- # Record as tool result
- tool_result = ToolResult(
- tool_name="rlm_repl",
- content=output or "(no output)",
- success=(
- not output.startswith("Error:")
- and not output.startswith("SyntaxError:")
- ),
- )
- all_tool_results.append(tool_result)
+ # Record the capability/rate/audit-gated REPL result.
+ all_tool_results.append(repl_result)
# Check for termination
if repl.is_terminated:
diff --git a/src/openjarvis/channels/slack_daemon.py b/src/openjarvis/channels/slack_daemon.py
index a2f028c3..e156b04e 100644
--- a/src/openjarvis/channels/slack_daemon.py
+++ b/src/openjarvis/channels/slack_daemon.py
@@ -51,7 +51,10 @@ def run_slack_daemon(
from slack_bolt.adapter.socket_mode import SocketModeHandler
from openjarvis.agents.deep_research import DeepResearchAgent
+ from openjarvis.core.config import load_config
+ from openjarvis.core.events import EventBus
from openjarvis.engine.ollama import OllamaEngine
+ from openjarvis.security import setup_security
from openjarvis.server.agent_manager_routes import (
_build_deep_research_tools,
)
@@ -62,13 +65,20 @@ def run_slack_daemon(
pid_path.write_text(str(os.getpid()))
# Build agent
- engine = OllamaEngine()
+ config = load_config()
+ bus = EventBus(record_history=False)
+ security = setup_security(config, OllamaEngine(), bus)
+ engine = security.engine
tools = _build_deep_research_tools(engine=engine, model=model)
agent = DeepResearchAgent(
engine=engine,
model=model,
tools=tools,
max_turns=5,
+ bus=bus,
+ capability_policy=security.capability_policy,
+ rate_limiter=security.rate_limiter,
+ agent_id="channel:slack",
)
logger.info("Slack daemon: agent ready with %d tools", len(tools))
diff --git a/src/openjarvis/cli/ask.py b/src/openjarvis/cli/ask.py
index 464f590c..58d0170b 100644
--- a/src/openjarvis/cli/ask.py
+++ b/src/openjarvis/cli/ask.py
@@ -355,6 +355,7 @@ def _run_agent(
temperature: float,
max_tokens: int,
capability_policy=None,
+ rate_limiter=None,
memory_files_config=None,
):
"""Instantiate and run an agent, returning the AgentResult."""
@@ -457,8 +458,22 @@ def _run_agent(
agent_kwargs["max_turns"] = config.agent.max_turns
agent_kwargs["interactive"] = True
agent_kwargs["confirm_callback"] = lambda prompt: True
- if capability_policy is not None:
- agent_kwargs["capability_policy"] = capability_policy
+ agent_kwargs["agent_id"] = agent_name
+ if capability_policy is not None:
+ agent_kwargs["capability_policy"] = capability_policy
+ if rate_limiter is not None:
+ agent_kwargs["rate_limiter"] = rate_limiter
+
+ from openjarvis.security.runtime import agent_security_kwargs
+
+ agent_kwargs.update(
+ agent_security_kwargs(
+ agent_cls,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_name,
+ )
+ )
# Wire the SystemPromptBuilder so SOUL.md / MEMORY.md / USER.md persona
# files actually reach the model. Only passed to agents whose __init__
@@ -478,6 +493,15 @@ def _run_agent(
)
agent = agent_cls(engine, model_name, **agent_kwargs)
+ from openjarvis.security.runtime import wire_agent_security
+
+ wire_agent_security(
+ agent,
+ bus=bus,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_name,
+ )
# Hold MCP transports alive for the agent's lifetime — without this
# reference they'd be garbage-collected when this function returns
# and the underlying HTTP connections would close mid-execution (#461
@@ -981,6 +1005,7 @@ def ask(
temperature,
max_tokens,
capability_policy=sec.capability_policy,
+ rate_limiter=getattr(sec, "rate_limiter", None),
memory_files_config=effective_mf,
)
except EngineContextLengthError as exc:
diff --git a/src/openjarvis/cli/channels_cmd.py b/src/openjarvis/cli/channels_cmd.py
index 5d653877..01170130 100644
--- a/src/openjarvis/cli/channels_cmd.py
+++ b/src/openjarvis/cli/channels_cmd.py
@@ -102,7 +102,10 @@ def imessage_start(
TwoStageRetriever,
)
from openjarvis.connectors.store import KnowledgeStore
+ from openjarvis.core.config import load_config
+ from openjarvis.core.events import EventBus
from openjarvis.engine.ollama import OllamaEngine
+ from openjarvis.security import setup_security
from openjarvis.tools.knowledge_search import (
KnowledgeSearchTool,
)
@@ -112,7 +115,10 @@ def imessage_start(
from openjarvis.tools.scan_chunks import ScanChunksTool
from openjarvis.tools.think import ThinkTool
- engine = OllamaEngine()
+ config = load_config()
+ bus = EventBus(record_history=False)
+ security = setup_security(config, OllamaEngine(), bus)
+ engine = security.engine
store = KnowledgeStore()
retriever = TwoStageRetriever(store)
tools = [
@@ -129,6 +135,10 @@ def imessage_start(
engine=engine,
model="qwen3.5:4b",
tools=tools,
+ bus=bus,
+ capability_policy=security.capability_policy,
+ rate_limiter=security.rate_limiter,
+ agent_id="channel:imessage",
)
def handler(text: str) -> str:
diff --git a/src/openjarvis/cli/chat_cmd.py b/src/openjarvis/cli/chat_cmd.py
index 7c767f89..493d80cd 100644
--- a/src/openjarvis/cli/chat_cmd.py
+++ b/src/openjarvis/cli/chat_cmd.py
@@ -186,6 +186,14 @@ def chat(
runtime_opts = ChatRuntimeOptions()
engine_kwargs = runtime_opts.to_engine_kwargs(engine_name=engine_name)
+ # Interactive chat is a first-class tool execution path. Apply the same
+ # configured engine guardrails, RBAC, rate limiting, and audit bus as ask,
+ # serve, and the SDK before constructing any agent.
+ from openjarvis.security import setup_security
+
+ security = setup_security(config, engine, bus)
+ engine = security.engine
+
# Resolve agent (optional)
agent = None
agent_key = agent_name or config.agent.default_agent
@@ -234,6 +242,17 @@ def chat(
kwargs["interactive"] = True
kwargs["confirm_callback"] = _confirm
+ from openjarvis.security.runtime import agent_security_kwargs
+
+ kwargs.update(
+ agent_security_kwargs(
+ agent_cls,
+ capability_policy=security.capability_policy,
+ rate_limiter=security.rate_limiter,
+ agent_id=agent_key,
+ )
+ )
+
import inspect as _inspect
if (
@@ -249,6 +268,15 @@ def chat(
)
agent = agent_cls(engine, model, **kwargs)
+ from openjarvis.security.runtime import wire_agent_security
+
+ wire_agent_security(
+ agent,
+ bus=bus,
+ capability_policy=security.capability_policy,
+ rate_limiter=security.rate_limiter,
+ agent_id=agent_key,
+ )
if agent is not None and engine_kwargs:
# Agents like NativeReActAgent do not accept engine_options
# in __init__; session opts live on BaseAgent._engine_options.
diff --git a/src/openjarvis/cli/deep_research_setup_cmd.py b/src/openjarvis/cli/deep_research_setup_cmd.py
index c1388780..00b61075 100644
--- a/src/openjarvis/cli/deep_research_setup_cmd.py
+++ b/src/openjarvis/cli/deep_research_setup_cmd.py
@@ -279,7 +279,10 @@ def _launch_chat(store: KnowledgeStore, console: Console) -> None:
"""Start an interactive Deep Research chat session."""
from openjarvis.agents.deep_research import DeepResearchAgent
from openjarvis.connectors.retriever import TwoStageRetriever
+ from openjarvis.core.config import load_config
+ from openjarvis.core.events import EventBus
from openjarvis.engine.ollama import OllamaEngine
+ from openjarvis.security import setup_security
from openjarvis.tools.knowledge_search import KnowledgeSearchTool
from openjarvis.tools.knowledge_sql import KnowledgeSQLTool
from openjarvis.tools.scan_chunks import ScanChunksTool
@@ -288,7 +291,10 @@ def _launch_chat(store: KnowledgeStore, console: Console) -> None:
console.print("\n[bold]Setting up Deep Research agent...[/bold]")
# Engine
- engine = OllamaEngine()
+ config = load_config()
+ bus = EventBus(record_history=False)
+ security = setup_security(config, OllamaEngine(), bus)
+ engine = security.engine
if not engine.health():
console.print(
"[red]Ollama is not running.[/red] Start it with: [bold]ollama serve[/bold]"
@@ -321,6 +327,10 @@ def _launch_chat(store: KnowledgeStore, console: Console) -> None:
model=_OLLAMA_MODEL,
tools=tools,
interactive=True,
+ bus=bus,
+ capability_policy=security.capability_policy,
+ rate_limiter=security.rate_limiter,
+ agent_id="cli:deep-research",
)
console.print(
diff --git a/src/openjarvis/cli/serve.py b/src/openjarvis/cli/serve.py
index 0ea1dc19..f73bd101 100644
--- a/src/openjarvis/cli/serve.py
+++ b/src/openjarvis/cli/serve.py
@@ -320,11 +320,14 @@ def serve(
if AgentRegistry.contains(agent_key):
agent_cls = AgentRegistry.get(agent_key)
agent_kwargs = {"bus": bus}
- if sec.capability_policy is not None:
- agent_kwargs["capability_policy"] = sec.capability_policy
# Load tools for agents that support them
if getattr(agent_cls, "accepts_tools", False):
+ agent_kwargs["agent_id"] = agent_key
+ if sec.capability_policy is not None:
+ agent_kwargs["capability_policy"] = sec.capability_policy
+ if sec.rate_limiter is not None:
+ agent_kwargs["rate_limiter"] = sec.rate_limiter
import openjarvis.tools # noqa: F401 # trigger registration
from openjarvis.core.registry import ToolRegistry
from openjarvis.tools._stubs import BaseTool
@@ -367,6 +370,17 @@ def serve(
if getattr(agent_cls, "accepts_tools", False):
agent_kwargs["max_turns"] = config.agent.max_turns
+ from openjarvis.security.runtime import agent_security_kwargs
+
+ agent_kwargs.update(
+ agent_security_kwargs(
+ agent_cls,
+ capability_policy=sec.capability_policy,
+ rate_limiter=sec.rate_limiter,
+ agent_id=agent_key,
+ )
+ )
+
# Wire the SystemPromptBuilder so SOUL.md / MEMORY.md / USER.md
# reach the model on the SERVE path too. ``ask.py`` has done
# this since the persona system landed; ``serve.py`` never did,
@@ -389,6 +403,15 @@ def serve(
)
agent = agent_cls(engine, model_name, **agent_kwargs)
+ from openjarvis.security.runtime import wire_agent_security
+
+ wire_agent_security(
+ agent,
+ bus=bus,
+ capability_policy=sec.capability_policy,
+ rate_limiter=sec.rate_limiter,
+ agent_id=agent_key,
+ )
# Pin MCP transports to the agent's lifetime so HTTP
# connections don't close mid-request (#461).
if mcp_clients:
@@ -476,6 +499,9 @@ def serve(
tools=_channel_tools,
mcp_tools=managed_mcp_tools,
_mcp_clients=mcp_clients,
+ capability_policy=sec.capability_policy,
+ audit_logger=sec.audit_logger,
+ rate_limiter=sec.rate_limiter,
)
_wire_system.wire_channel(channel_bridge)
@@ -593,7 +619,15 @@ def serve(
logger.debug("Scheduler session store init failed: %s", exc)
_sched_tool_executor = (
- ToolExecutor(resolved_tools, bus) if resolved_tools else None
+ ToolExecutor(
+ resolved_tools,
+ bus,
+ capability_policy=sec.capability_policy,
+ agent_id=agent_key or "scheduler",
+ rate_limiter=sec.rate_limiter,
+ )
+ if resolved_tools
+ else None
)
system = JarvisSystem(
@@ -612,6 +646,8 @@ def serve(
trace_store=_trace_store,
session_store=_sched_session_store,
capability_policy=sec.capability_policy,
+ audit_logger=sec.audit_logger,
+ rate_limiter=sec.rate_limiter,
agent_manager=agent_manager,
agent_executor=executor,
_mcp_clients=mcp_clients,
@@ -713,6 +749,9 @@ def serve(
agent_scheduler=agent_scheduler,
mcp_tools=managed_mcp_tools,
mcp_clients=mcp_clients,
+ capability_policy=sec.capability_policy,
+ rate_limiter=sec.rate_limiter,
+ audit_logger=sec.audit_logger,
api_key=api_key,
webhook_config=webhook_config,
cors_origins=config.server.cors_origins,
diff --git a/src/openjarvis/core/config.py b/src/openjarvis/core/config.py
index 4e664dcf..212153c3 100644
--- a/src/openjarvis/core/config.py
+++ b/src/openjarvis/core/config.py
@@ -1424,6 +1424,7 @@ class CapabilitiesConfig:
enabled: bool = False
policy_path: str = ""
+ default_deny: bool = False
@dataclass(slots=True)
@@ -1477,6 +1478,7 @@ _SECURITY_PROFILES: Dict[str, Dict[str, Dict[str, Any]]] = {
"rate_limit_enabled": True,
"local_engine_bypass": False,
"local_tool_bypass": False,
+ "capabilities": {"enabled": True, "default_deny": True},
},
"server": {
"host": "127.0.0.1",
@@ -1490,6 +1492,7 @@ _SECURITY_PROFILES: Dict[str, Dict[str, Dict[str, Any]]] = {
"rate_limit_burst": 5,
"local_engine_bypass": False,
"local_tool_bypass": False,
+ "capabilities": {"enabled": True, "default_deny": True},
},
"server": {
"host": "0.0.0.0",
@@ -1523,6 +1526,18 @@ def apply_security_profile(
pdef = _SECURITY_PROFILES[profile]
for key, value in pdef.get("security", {}).items():
+ if key == "capabilities" and isinstance(value, dict):
+ # Preserve explicitly selected fields while inheriting the
+ # profile's remaining defaults. A policy_path alone must not
+ # silently disable the profile's capability gate.
+ if "capabilities" in _overrides:
+ continue
+ for cap_key, cap_value in value.items():
+ if f"capabilities.{cap_key}" not in _overrides and hasattr(
+ security_cfg.capabilities, cap_key
+ ):
+ setattr(security_cfg.capabilities, cap_key, cap_value)
+ continue
if key not in _overrides and hasattr(security_cfg, key):
setattr(security_cfg, key, value)
@@ -2110,7 +2125,13 @@ def load_config(path: Optional[Path] = None) -> JarvisConfig:
setattr(cfg, key, data[key])
# Expand security profile (user TOML overrides take precedence)
- _user_security_keys = set(data.get("security", {}).keys())
+ _security_data = data.get("security", {})
+ _user_security_keys = set(_security_data)
+ if isinstance(_security_data.get("capabilities"), dict):
+ _user_security_keys.discard("capabilities")
+ _user_security_keys.update(
+ f"capabilities.{key}" for key in _security_data["capabilities"]
+ )
apply_security_profile(cfg.security, cfg.server, overrides=_user_security_keys)
# Mining: dedicated parser for tagged-union submit_target
diff --git a/src/openjarvis/core/events.py b/src/openjarvis/core/events.py
index 231a7be4..80f1d7bd 100644
--- a/src/openjarvis/core/events.py
+++ b/src/openjarvis/core/events.py
@@ -50,6 +50,7 @@ class EventType(str, Enum):
LOOP_GUARD_TRIGGERED = "loop_guard_triggered"
CAPABILITY_DENIED = "capability_denied"
TAINT_VIOLATION = "taint_violation"
+ RATE_LIMITED = "rate_limited"
# Phase 15 — Workflow, Skills, Sessions
WORKFLOW_START = "workflow_start"
WORKFLOW_NODE_START = "workflow_node_start"
diff --git a/src/openjarvis/learning/intelligence/orchestrator/environment.py b/src/openjarvis/learning/intelligence/orchestrator/environment.py
index 7f731164..56867e49 100644
--- a/src/openjarvis/learning/intelligence/orchestrator/environment.py
+++ b/src/openjarvis/learning/intelligence/orchestrator/environment.py
@@ -9,8 +9,9 @@ both training and evaluation.
from __future__ import annotations
import time
-from typing import List, Tuple
+from typing import Any, List, Optional, Tuple
+from openjarvis.core.events import EventBus
from openjarvis.core.types import ToolCall
from openjarvis.learning.intelligence.orchestrator.types import (
EpisodeState,
@@ -19,6 +20,8 @@ from openjarvis.learning.intelligence.orchestrator.types import (
)
from openjarvis.tools._stubs import BaseTool, ToolExecutor
+_LEARNING_AGENT_ID = "learning"
+
class OrchestratorEnvironment:
"""RL environment that executes tools via OpenJarvis ``ToolExecutor``.
@@ -35,9 +38,23 @@ class OrchestratorEnvironment:
self,
tools: List[BaseTool],
max_turns: int = 10,
+ *,
+ bus: Optional[EventBus] = None,
+ capability_policy: Optional[Any] = None,
+ rate_limiter: Optional[Any] = None,
+ agent_id: str = _LEARNING_AGENT_ID,
) -> None:
self._tools = tools
- self._executor = ToolExecutor(tools)
+ # Training/evaluation must not become an enforcement bypass. A stable
+ # non-empty identity also makes capability, rate-limit and audit events
+ # attributable instead of pooling them under the anonymous key.
+ self._executor = ToolExecutor(
+ tools,
+ bus,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_id or _LEARNING_AGENT_ID,
+ )
self._max_turns = max_turns
def reset(self, task: str) -> EpisodeState:
diff --git a/src/openjarvis/mcp/server.py b/src/openjarvis/mcp/server.py
index 25500372..ebac6460 100644
--- a/src/openjarvis/mcp/server.py
+++ b/src/openjarvis/mcp/server.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import logging
from typing import Any, Dict, List, Optional
+from openjarvis.core.events import EventBus
from openjarvis.core.types import ToolCall
from openjarvis.mcp.protocol import (
INTERNAL_ERROR,
@@ -17,6 +18,8 @@ from openjarvis.tools._stubs import BaseTool, ToolExecutor
logger = logging.getLogger(__name__)
+_MCP_AGENT_ID = "mcp"
+
# Tool annotation hints per MCP spec 2025-11-25
_TOOL_ANNOTATIONS: Dict[str, Dict[str, Any]] = {
"memory_store": {"destructiveHint": True, "readOnlyHint": False},
@@ -51,11 +54,34 @@ class MCPServer:
SERVER_VERSION = "0.1.0"
PROTOCOL_VERSION = "2025-11-25"
- def __init__(self, tools: Optional[List[BaseTool]] = None) -> None:
+ def __init__(
+ self,
+ tools: Optional[List[BaseTool]] = None,
+ *,
+ bus: Optional[EventBus] = None,
+ capability_policy: Optional[Any] = None,
+ rate_limiter: Optional[Any] = None,
+ agent_id: str = _MCP_AGENT_ID,
+ ) -> None:
+ """Create an MCP server with the same dispatch gates as other agents.
+
+ ``agent_id`` is deliberately non-empty by default: capability policy,
+ rate-limit and audit records must never collapse MCP traffic into the
+ anonymous ``""`` identity. Callers that enable a security profile
+ pass its policy and limiter here; ``ToolExecutor`` then applies both
+ declared and canonical built-in capability requirements before a tool
+ can run.
+ """
if tools is None:
tools = self._auto_discover_tools()
self._tools: Dict[str, BaseTool] = {t.spec.name: t for t in tools}
- self._executor = ToolExecutor(tools)
+ self._executor = ToolExecutor(
+ tools,
+ bus,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_id or _MCP_AGENT_ID,
+ )
@staticmethod
def _auto_discover_tools() -> List[BaseTool]:
diff --git a/src/openjarvis/sdk.py b/src/openjarvis/sdk.py
index 5f17216e..657a6bde 100644
--- a/src/openjarvis/sdk.py
+++ b/src/openjarvis/sdk.py
@@ -173,6 +173,7 @@ class Jarvis:
self._telem_store: Optional[TelemetryStore] = None
self._audit_logger: Any = None
self._capability_policy: Any = None
+ self._rate_limiter: Any = None
self.memory = MemoryHandle(self._config)
# Set up telemetry
@@ -221,6 +222,7 @@ class Jarvis:
engine = sec.engine
self._audit_logger = sec.audit_logger
self._capability_policy = sec.capability_policy
+ self._rate_limiter = sec.rate_limiter
# Wrap engine with InstrumentedEngine for telemetry + energy
energy_monitor = None
@@ -485,9 +487,16 @@ class Jarvis:
if getattr(agent_cls, "accepts_tools", False):
agent_kwargs["tools"] = tool_objects
agent_kwargs["max_turns"] = self._config.agent.max_turns
-
- if self._capability_policy is not None:
- agent_kwargs["capability_policy"] = self._capability_policy
+ from openjarvis.security.runtime import agent_security_kwargs
+
+ agent_kwargs.update(
+ agent_security_kwargs(
+ agent_cls,
+ capability_policy=self._capability_policy,
+ rate_limiter=self._rate_limiter,
+ agent_id=agent_name,
+ )
+ )
# Inject DigestConfig for morning_digest agent
if agent_name == "morning_digest" and hasattr(self._config, "digest"):
@@ -532,6 +541,15 @@ class Jarvis:
)
agent_obj = agent_cls(self._engine, model_name, **agent_kwargs)
+ from openjarvis.security.runtime import wire_agent_security
+
+ wire_agent_security(
+ agent_obj,
+ bus=self._bus,
+ capability_policy=self._capability_policy,
+ rate_limiter=self._rate_limiter,
+ agent_id=agent_name,
+ )
ctx = AgentContext()
# Context injection
diff --git a/src/openjarvis/security/__init__.py b/src/openjarvis/security/__init__.py
index b89a4425..dcad145b 100644
--- a/src/openjarvis/security/__init__.py
+++ b/src/openjarvis/security/__init__.py
@@ -19,6 +19,7 @@ class SecurityContext:
engine: Any
capability_policy: Any = None
audit_logger: Any = None
+ rate_limiter: Any = None
def setup_security(
@@ -68,9 +69,49 @@ def setup_security(
cap_policy = CapabilityPolicy(
policy_path=config.security.capabilities.policy_path or None,
+ default_deny=config.security.capabilities.default_deny,
)
+ # No explicit policy file: grant a conservative baseline to the
+ # "_default" wildcard agent so default-deny doesn't silently
+ # break every managed agent (whose UUIDs aren't known ahead of
+ # time). Read/fetch/memory only — writes, code execution, and
+ # admin tools require an explicit per-agent grant.
+ if (
+ config.security.capabilities.default_deny
+ and not config.security.capabilities.policy_path
+ ):
+ for cap in (
+ "file:read",
+ "network:fetch",
+ "memory:read",
+ "memory:write",
+ ):
+ cap_policy.grant("_default", cap)
except Exception as exc:
- logger.debug("Failed to set up capability policy: %s", exc)
+ # Explicitly enabled enforcement is a contract in every profile.
+ # Missing native support or an invalid policy must not produce an
+ # unrestricted executor merely because the profile is personal.
+ raise RuntimeError("Capability policy initialization failed") from exc
+
+ # Rate limiter — config.security.rate_limit_* were previously read by
+ # nothing; this is the first thing in the codebase that actually turns
+ # them into an enforced limiter.
+ rate_limiter = None
+ if config.security.rate_limit_enabled:
+ try:
+ from openjarvis.security.rate_limiter import RateLimitConfig, RateLimiter
+
+ rate_limiter = RateLimiter(
+ RateLimitConfig(
+ requests_per_minute=config.security.rate_limit_rpm,
+ burst_size=config.security.rate_limit_burst,
+ enabled=True,
+ )
+ )
+ except Exception as exc:
+ if config.security.profile in {"shared", "server"}:
+ raise RuntimeError("Rate limiter initialization failed") from exc
+ logger.warning("Failed to set up rate limiter: %s", exc)
# Audit logger
audit = None
@@ -86,6 +127,7 @@ def setup_security(
engine=engine,
capability_policy=cap_policy,
audit_logger=audit,
+ rate_limiter=rate_limiter,
)
diff --git a/src/openjarvis/security/audit.py b/src/openjarvis/security/audit.py
index 40df1c90..85f3da97 100644
--- a/src/openjarvis/security/audit.py
+++ b/src/openjarvis/security/audit.py
@@ -53,7 +53,10 @@ class AuditLogger:
secure_create(self._db_path)
self._db_lock = threading.RLock()
- self._conn = sqlite3.connect(str(self._db_path), check_same_thread=False)
+ self._conn = sqlite3.connect(
+ str(self._db_path), check_same_thread=False, timeout=30.0
+ )
+ self._conn.execute("PRAGMA busy_timeout = 30000")
self._conn.execute(
"""
CREATE TABLE IF NOT EXISTS security_events (
@@ -75,6 +78,9 @@ class AuditLogger:
bus.subscribe(EventType.SECURITY_SCAN, self._on_event)
bus.subscribe(EventType.SECURITY_ALERT, self._on_event)
bus.subscribe(EventType.SECURITY_BLOCK, self._on_event)
+ bus.subscribe(EventType.TOOL_CALL_END, self._on_tool_event)
+ bus.subscribe(EventType.CAPABILITY_DENIED, self._on_tool_event)
+ bus.subscribe(EventType.RATE_LIMITED, self._on_tool_event)
@_db_locked
def _migrate_schema(self) -> None:
@@ -144,7 +150,7 @@ class AuditLogger:
),
)
self._conn.commit()
- except Exception:
+ except BaseException:
self._conn.rollback()
raise
@@ -290,5 +296,33 @@ class AuditLogger:
)
self.log(sec_event)
+ def _on_tool_event(self, event: Event) -> None:
+ """Handle a TOOL_CALL_END / CAPABILITY_DENIED / RATE_LIMITED event."""
+ data = event.data
+ if event.event_type == EventType.TOOL_CALL_END:
+ success = bool(data.get("success"))
+ sec_event = SecurityEvent(
+ event_type=SecurityEventType.TOOL_EXECUTED,
+ timestamp=event.timestamp,
+ findings=[],
+ content_preview=(
+ f"tool={data.get('tool', '')} agent={data.get('agent', '')}"
+ ),
+ action_taken="success" if success else "failure",
+ )
+ else:
+ # CAPABILITY_DENIED or RATE_LIMITED — both represent a blocked
+ # tool call and share the same TOOL_BLOCKED category.
+ sec_event = SecurityEvent(
+ event_type=SecurityEventType.TOOL_BLOCKED,
+ timestamp=event.timestamp,
+ findings=[],
+ content_preview=(
+ f"tool={data.get('tool', '')} agent={data.get('agent_id', '')}"
+ ),
+ action_taken=event.event_type.value,
+ )
+ self.log(sec_event)
+
__all__ = ["AuditLogger"]
diff --git a/src/openjarvis/security/capabilities.py b/src/openjarvis/security/capabilities.py
index d5030d8a..5e655cf2 100644
--- a/src/openjarvis/security/capabilities.py
+++ b/src/openjarvis/security/capabilities.py
@@ -8,7 +8,7 @@ import logging
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
-from typing import Dict, List, Optional
+from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
@@ -91,11 +91,26 @@ class CapabilityPolicy:
policy.deny.append(capability)
self._rust_impl.deny(agent_id, capability)
+ _DEFAULT_AGENT = "_default"
+
def check(self, agent_id: str, capability: str, resource: str = "") -> bool:
"""Check whether *agent_id* has *capability* for *resource*.
- Returns True if allowed, False if denied.
+ Falls back to the ``_default`` wildcard agent's grants only when
+ *agent_id* has no explicit policy of its own. This lets a baseline be
+ granted once via
+ ``grant("_default", ...)`` instead of needing to know every
+ dynamically-created managed-agent UUID ahead of time while preserving
+ the invariant that an agent-specific denial always wins.
"""
+ if (
+ not agent_id
+ or agent_id == self._DEFAULT_AGENT
+ or agent_id in self._policies
+ ):
+ return self._rust_impl.check(agent_id, capability, resource)
+ if self._DEFAULT_AGENT in self._policies:
+ return self._rust_impl.check(self._DEFAULT_AGENT, capability, resource)
return self._rust_impl.check(agent_id, capability, resource)
def _check_python(self, agent_id: str, capability: str, resource: str = "") -> bool:
@@ -132,23 +147,44 @@ class CapabilityPolicy:
return list(self._policies.keys())
def _load_file(self, path: Path) -> None:
- """Load policy from a JSON file."""
- if not path.exists():
- return
- try:
- data = json.loads(path.read_text())
- for agent_data in data.get("agents", []):
- agent_id = agent_data["agent_id"]
- for grant_data in agent_data.get("grants", []):
- self.grant(
- agent_id,
- grant_data["capability"],
- grant_data.get("pattern", "*"),
+ """Load an explicitly configured policy, rejecting incomplete policy data."""
+ # A missing/malformed file must not silently discard configured denies.
+ # Validate the complete document before applying any grants.
+ data = json.loads(path.read_text())
+ if not isinstance(data, dict) or not isinstance(data.get("agents"), list):
+ raise ValueError("Capability policy must contain an agents list")
+ for agent_data in data["agents"]:
+ if not isinstance(agent_data, dict):
+ raise ValueError("Capability policy agent must be an object")
+ agent_id = agent_data.get("agent_id")
+ if not isinstance(agent_id, str) or not agent_id.strip():
+ raise ValueError("Capability policy agent_id must be a nonempty string")
+ grants = agent_data.get("grants", [])
+ denied = agent_data.get("deny", [])
+ if not isinstance(grants, list) or not isinstance(denied, list):
+ raise ValueError("Capability policy grants and deny must be lists")
+ for grant in grants:
+ if (
+ not isinstance(grant, dict)
+ or not isinstance(grant.get("capability"), str)
+ or not grant["capability"].strip()
+ or not isinstance(grant.get("pattern", "*"), str)
+ ):
+ raise ValueError(
+ "Capability policy grant must specify a capability"
)
- for denied in agent_data.get("deny", []):
- self.deny(agent_id, denied)
- except (json.JSONDecodeError, KeyError, TypeError) as exc:
- logger.warning("Failed to parse capability policy: %s", exc)
+ if any(not isinstance(cap, str) or not cap.strip() for cap in denied):
+ raise ValueError("Capability policy deny entries must be strings")
+
+ for agent_data in data["agents"]:
+ agent_id = agent_data["agent_id"]
+ # An explicit empty policy is still an identity-specific policy;
+ # it must not accidentally inherit the wildcard's grants.
+ self._policies.setdefault(agent_id, AgentPolicy(agent_id=agent_id))
+ for grant in agent_data.get("grants", []):
+ self.grant(agent_id, grant["capability"], grant.get("pattern", "*"))
+ for denied in agent_data.get("deny", []):
+ self.deny(agent_id, denied)
def save(self, path: Path) -> None:
"""Save policy to a JSON file."""
@@ -167,25 +203,142 @@ class CapabilityPolicy:
path.write_text(json.dumps({"agents": agents}, indent=2))
-# Default capability requirements for built-in tools
+# Canonical capability requirements for every in-tree tool. This table is a
+# security floor: ToolSpec declarations may add requirements, but they may not
+# weaken these. Keep explicitly-safe tools in the table with an empty list so
+# an omitted future built-in can be distinguished from a reviewed safe one.
DEFAULT_TOOL_CAPABILITIES: Dict[str, List[str]] = {
+ "agent_kill": [Capability.SYSTEM_ADMIN],
+ "agent_list": [Capability.SYSTEM_ADMIN],
+ "agent_send": [Capability.SYSTEM_ADMIN],
+ "agent_spawn": [Capability.SYSTEM_ADMIN],
+ "apply_patch": [Capability.FILE_WRITE],
+ "audio_transcribe": [Capability.FILE_READ, Capability.NETWORK_FETCH],
+ "browser_axtree": [Capability.NETWORK_FETCH],
+ "browser_click": [Capability.NETWORK_FETCH],
+ "browser_extract": [Capability.NETWORK_FETCH],
+ "browser_navigate": [Capability.NETWORK_FETCH],
+ "browser_screenshot": [Capability.NETWORK_FETCH],
+ "browser_type": [Capability.NETWORK_FETCH],
+ "calculator": [],
+ "calendar_search": [Capability.FILE_READ],
+ "calendar_upcoming": [Capability.FILE_READ],
+ "cancel_scheduled_task": [Capability.SCHEDULE_CREATE],
+ "channel_list": [Capability.SYSTEM_ADMIN],
+ "channel_send": [Capability.CHANNEL_SEND],
+ "channel_status": [Capability.SYSTEM_ADMIN],
+ "check_permission": [Capability.MEMORY_READ],
+ "code_interpreter": [Capability.CODE_EXECUTE],
+ "code_interpreter_docker": [Capability.CODE_EXECUTE],
+ "db_query": [Capability.CODE_EXECUTE],
+ "digest_collect": [Capability.MEMORY_READ, Capability.NETWORK_FETCH],
+ "docker_shell_exec": [Capability.CODE_EXECUTE],
+ "execute_pending_actions": [
+ Capability.SYSTEM_ADMIN,
+ Capability.CHANNEL_SEND,
+ Capability.NETWORK_FETCH,
+ ],
"file_read": [Capability.FILE_READ],
- "web_search": [Capability.NETWORK_FETCH],
+ "file_write": [Capability.FILE_WRITE],
+ "get_pending_actions": [Capability.MEMORY_READ],
"get_weather": [Capability.NETWORK_FETCH],
- "code_interpreter": [Capability.CODE_EXECUTE],
- "memory_store": [Capability.MEMORY_WRITE],
+ "git_commit": [Capability.FILE_WRITE],
+ "git_diff": [Capability.FILE_READ],
+ "git_log": [Capability.FILE_READ],
+ "git_status": [Capability.FILE_READ],
+ "http_request": [Capability.NETWORK_FETCH],
+ "image_generate": [Capability.NETWORK_FETCH, Capability.FILE_WRITE],
+ "kg_add_entity": [Capability.MEMORY_WRITE],
+ "kg_add_relation": [Capability.MEMORY_WRITE],
+ "kg_neighbors": [Capability.MEMORY_READ],
+ "kg_query": [Capability.MEMORY_READ],
+ "knowledge_search": [Capability.MEMORY_READ],
+ "knowledge_sql": [Capability.MEMORY_READ],
+ "list_scheduled_tasks": [Capability.SCHEDULE_CREATE],
+ "llm": [Capability.NETWORK_FETCH],
+ "memory_index": [Capability.MEMORY_WRITE],
+ "memory_manage": [Capability.MEMORY_READ, Capability.MEMORY_WRITE],
"memory_retrieve": [Capability.MEMORY_READ],
"memory_search": [Capability.MEMORY_READ],
- "memory_index": [Capability.MEMORY_WRITE],
+ "memory_store": [Capability.MEMORY_WRITE],
+ "pause_scheduled_task": [Capability.SCHEDULE_CREATE],
+ "pdf_extract": [Capability.FILE_READ],
+ "queue_action": [Capability.MEMORY_WRITE],
+ "record_decision": [Capability.SYSTEM_ADMIN, Capability.MEMORY_WRITE],
+ "repl": [Capability.CODE_EXECUTE],
+ "resume_scheduled_task": [Capability.SCHEDULE_CREATE],
+ "retrieval": [Capability.MEMORY_READ],
+ "scan_chunks": [Capability.MEMORY_READ],
"schedule_task": [Capability.SCHEDULE_CREATE],
- "channel_send": [Capability.CHANNEL_SEND],
+ "shell_exec": [Capability.CODE_EXECUTE],
+ "skill_manage": [Capability.FILE_READ, Capability.FILE_WRITE],
+ "text_to_speech": [Capability.NETWORK_FETCH, Capability.FILE_WRITE],
+ "think": [],
+ "user_profile_manage": [Capability.FILE_READ, Capability.FILE_WRITE],
+ "web_search": [Capability.NETWORK_FETCH],
+}
+
+_SAFE_BUILTIN_PROVENANCE = {
+ "calculator": ("openjarvis.tools.calculator", "CalculatorTool"),
+ "think": ("openjarvis.tools.think", "ThinkTool"),
}
+def canonical_tool_capabilities(tool: Any) -> List[str]:
+ """Return the non-bypassable capability floor for *tool*.
+
+ Third-party tools remain governed by their ToolSpec. An in-tree tool that
+ was newly registered without being inventoried fails closed as
+ ``system:admin`` instead of silently becoming unrestricted.
+ """
+ module = type(tool).__module__
+ name = tool.spec.name
+ is_builtin = (
+ module == "openjarvis.tools"
+ or module.startswith("openjarvis.tools.")
+ or module == "openjarvis.scheduler.tools"
+ )
+ if module == "openjarvis.tools.mcp_adapter":
+ # MCP tool names are remote-controlled. Resolve adapter provenance
+ # before the name table so a server cannot impersonate a reviewed-safe
+ # local tool such as ``calculator`` or ``think``.
+ return [Capability.TOOL_INVOKE]
+ if is_builtin:
+ if name in DEFAULT_TOOL_CAPABILITIES:
+ canonical = list(DEFAULT_TOOL_CAPABILITIES[name])
+ expected = _SAFE_BUILTIN_PROVENANCE.get(name)
+ if (
+ expected is not None
+ and (
+ module,
+ type(tool).__name__,
+ )
+ != expected
+ ):
+ logger.error(
+ "Tool %r claimed reviewed-safe built-in provenance from %s.%s",
+ name,
+ module,
+ type(tool).__name__,
+ )
+ return [Capability.SYSTEM_ADMIN]
+ return canonical
+ logger.error("Built-in tool %r has no canonical capability inventory", name)
+ return [Capability.SYSTEM_ADMIN]
+ if name in DEFAULT_TOOL_CAPABILITIES:
+ canonical = list(DEFAULT_TOOL_CAPABILITIES[name])
+ # Third-party tools that collide with a privileged name retain its
+ # security floor. Reviewed-safe names are safe only for their in-tree
+ # implementation and therefore fail closed on foreign provenance.
+ return canonical or [Capability.SYSTEM_ADMIN]
+ return []
+
+
__all__ = [
"AgentPolicy",
"Capability",
"CapabilityGrant",
"CapabilityPolicy",
+ "canonical_tool_capabilities",
"DEFAULT_TOOL_CAPABILITIES",
]
diff --git a/src/openjarvis/security/runtime.py b/src/openjarvis/security/runtime.py
new file mode 100644
index 00000000..c9927188
--- /dev/null
+++ b/src/openjarvis/security/runtime.py
@@ -0,0 +1,206 @@
+"""Shared helpers for securing agent and direct tool execution paths."""
+
+from __future__ import annotations
+
+import inspect
+import json
+import uuid
+from typing import Any, Dict, Iterable
+
+
+def _accepts_kwarg(agent_cls: Any, name: str) -> bool:
+ """Return whether ``agent_cls.__init__`` accepts *name*."""
+ try:
+ parameters = inspect.signature(agent_cls.__init__).parameters
+ except (TypeError, ValueError):
+ return False
+ return name in parameters or any(
+ parameter.kind == inspect.Parameter.VAR_KEYWORD
+ for parameter in parameters.values()
+ )
+
+
+def agent_security_kwargs(
+ agent_cls: Any,
+ *,
+ capability_policy: Any = None,
+ rate_limiter: Any = None,
+ agent_id: str = "",
+) -> Dict[str, Any]:
+ """Build supported tool-security kwargs for an agent constructor.
+
+ Plain agents do not own a ToolExecutor, so passing tool-only security
+ kwargs to them is both ineffective and constructor-breaking. Tool-capable
+ agents receive only the kwargs their constructor explicitly supports (or
+ accepts via ``**kwargs``); :func:`wire_agent_security` is the final backstop
+ for custom tool agents that construct an executor without exposing those
+ parameters.
+ """
+ if not (
+ getattr(agent_cls, "accepts_tools", False)
+ or getattr(agent_cls, "uses_direct_operations", False)
+ or getattr(agent_cls, "required_capabilities", ())
+ ):
+ return {}
+
+ values = {
+ "capability_policy": capability_policy,
+ "rate_limiter": rate_limiter,
+ "agent_id": agent_id,
+ }
+ return {
+ name: value
+ for name, value in values.items()
+ if value is not None and _accepts_kwarg(agent_cls, name)
+ }
+
+
+def wire_agent_security(
+ agent: Any,
+ *,
+ bus: Any = None,
+ capability_policy: Any = None,
+ rate_limiter: Any = None,
+ agent_id: str = "",
+ overwrite: bool = True,
+ synchronize_runtime_cache: bool = False,
+) -> None:
+ """Wire runtime security into an already-created agent and executor."""
+ if agent is None:
+ return
+ if bus is not None:
+ # The audit logger subscribes to this runtime bus. An executor left on
+ # a stale/None bus can enforce policy but silently lose its audit trail.
+ agent._bus = bus
+ if capability_policy is not None and (
+ overwrite or getattr(agent, "_capability_policy", None) is None
+ ):
+ agent._capability_policy = capability_policy
+ if rate_limiter is not None and (
+ overwrite or getattr(agent, "_rate_limiter", None) is None
+ ):
+ agent._rate_limiter = rate_limiter
+ if agent_id and (overwrite or not getattr(agent, "_runtime_agent_id", "")):
+ agent._runtime_agent_id = agent_id
+
+ if synchronize_runtime_cache:
+ # Some agents (notably RLM) cache construction-time primitives for
+ # executors created lazily inside run(). A server factory wiring a
+ # prebuilt agent must synchronize those caches with the effective
+ # runtime values or the lazy executor silently falls back to the
+ # original None/default identity. Preserve explicit per-agent policy
+ # and limiter values selected above when overwrite=False.
+ if bus is not None and hasattr(agent, "_runtime_bus"):
+ agent._runtime_bus = bus
+ if hasattr(agent, "_runtime_capability_policy"):
+ agent._runtime_capability_policy = getattr(
+ agent,
+ "_capability_policy",
+ capability_policy,
+ )
+ if hasattr(agent, "_runtime_rate_limiter"):
+ agent._runtime_rate_limiter = getattr(
+ agent,
+ "_rate_limiter",
+ rate_limiter,
+ )
+ if agent_id:
+ agent._runtime_agent_id = agent_id
+
+ executor = getattr(agent, "_executor", None)
+ if executor is None:
+ return
+ if bus is not None:
+ executor._bus = bus
+ if capability_policy is not None and (
+ overwrite or getattr(executor, "_capability_policy", None) is None
+ ):
+ executor._capability_policy = capability_policy
+ if rate_limiter is not None and (
+ overwrite or getattr(executor, "_rate_limiter", None) is None
+ ):
+ executor._rate_limiter = rate_limiter
+ if agent_id and (
+ overwrite or synchronize_runtime_cache or not getattr(executor, "_agent_id", "")
+ ):
+ # A prebuilt agent crossing a server/runtime boundary must use the
+ # boundary identity for both its direct-operation cache and its
+ # already-created ToolExecutor. Otherwise a class-default identity
+ # (for example ``orchestrator``) can consume grants intended for a
+ # different principal even though the server labels the run with
+ # ``agent_name``.
+ executor._agent_id = agent_id
+
+
+def execute_secured_tool(
+ tool: Any,
+ params: Dict[str, Any],
+ *,
+ bus: Any = None,
+ capability_policy: Any = None,
+ rate_limiter: Any = None,
+ agent_id: str,
+):
+ """Run one direct operation through the canonical ToolExecutor gates."""
+ from openjarvis.core.types import ToolCall
+ from openjarvis.tools._stubs import ToolExecutor
+
+ executor = ToolExecutor(
+ [tool],
+ bus=bus,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_id,
+ )
+ return executor.execute(
+ ToolCall(
+ id=f"direct-{uuid.uuid4().hex[:12]}",
+ name=tool.spec.name,
+ arguments=json.dumps(params),
+ )
+ )
+
+
+def authorize_secured_operation(
+ operation: str,
+ required_capabilities: Iterable[str],
+ *,
+ bus: Any = None,
+ capability_policy: Any = None,
+ rate_limiter: Any = None,
+ agent_id: str,
+):
+ """Authorize one non-``BaseTool`` operation through standard gates."""
+ from openjarvis.core.types import ToolResult
+ from openjarvis.tools._stubs import BaseTool, ToolSpec
+
+ capabilities = list(dict.fromkeys(str(cap) for cap in required_capabilities))
+
+ class _OperationGate(BaseTool):
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name=operation,
+ description="Authorize a direct agent runtime operation.",
+ required_capabilities=capabilities,
+ )
+
+ def execute(self, **params: Any) -> ToolResult:
+ return ToolResult(tool_name=operation, content="authorized")
+
+ return execute_secured_tool(
+ _OperationGate(),
+ {},
+ bus=bus,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=agent_id,
+ )
+
+
+__all__ = [
+ "agent_security_kwargs",
+ "authorize_secured_operation",
+ "execute_secured_tool",
+ "wire_agent_security",
+]
diff --git a/src/openjarvis/security/types.py b/src/openjarvis/security/types.py
index dd73df2f..775c9ec7 100644
--- a/src/openjarvis/security/types.py
+++ b/src/openjarvis/security/types.py
@@ -35,6 +35,7 @@ class SecurityEventType(str, Enum):
PII_DETECTED = "pii_detected"
SENSITIVE_FILE_BLOCKED = "sensitive_file_blocked"
TOOL_BLOCKED = "tool_blocked"
+ TOOL_EXECUTED = "tool_executed"
# ---------------------------------------------------------------------------
diff --git a/src/openjarvis/server/agent_manager_routes.py b/src/openjarvis/server/agent_manager_routes.py
index a66913ce..a38df76b 100644
--- a/src/openjarvis/server/agent_manager_routes.py
+++ b/src/openjarvis/server/agent_manager_routes.py
@@ -238,6 +238,8 @@ class _LightweightSystem:
self.model = model
self.config = config
self._runtime = runtime
+ self.capability_policy = getattr(runtime, "capability_policy", None)
+ self.rate_limiter = getattr(runtime, "rate_limiter", None)
# Wire the configured memory backend so an agent's memory_store /
# memory_retrieve tools work when the tick runs through the server.
# The executor injects system.memory_backend into those tools; this
@@ -1018,6 +1020,10 @@ async def _stream_managed_agent(
engine=engine,
model=model,
tools=dr_tools,
+ bus=getattr(app_state, "bus", None),
+ capability_policy=getattr(app_state, "capability_policy", None),
+ rate_limiter=getattr(app_state, "rate_limiter", None),
+ agent_id=agent_id,
max_turns=int(config.get("max_turns", 8)),
temperature=float(config.get("temperature", 0.3)),
interactive=True,
@@ -1302,11 +1308,18 @@ async def _stream_managed_agent(
from openjarvis.tools._stubs import ToolExecutor
resolved_by_name = resolved_toolkit.by_name
+ # Previously constructed with no capability_policy/rate_limiter/agent_id
+ # at all — this is the live SSE chat path for managed agents (what
+ # Tailscale/remote exposure actually hits), so tool calls made here ran
+ # with zero RBAC gating and zero rate limiting regardless of config.
stream_tool_executor = ToolExecutor(
tools=resolved_toolkit.instances,
bus=bus,
interactive=True,
confirm_callback=lambda _prompt: True,
+ capability_policy=getattr(app_state, "capability_policy", None),
+ rate_limiter=getattr(app_state, "rate_limiter", None),
+ agent_id=agent_id,
)
# Forward any per-agent sampler params (repetition_penalty, top_p, …) so
@@ -1857,6 +1870,16 @@ def create_agent_manager_router(
engine=engine,
model=getattr(engine, "_model", ""),
tools=tools,
+ bus=getattr(request.app.state, "bus", None),
+ capability_policy=getattr(
+ request.app.state,
+ "capability_policy",
+ None,
+ ),
+ rate_limiter=getattr(
+ request.app.state, "rate_limiter", None
+ ),
+ agent_id=agent_id,
interactive=True,
confirm_callback=lambda _prompt: True,
)
@@ -1930,6 +1953,16 @@ def create_agent_manager_router(
engine=engine,
model=model_name,
tools=tools,
+ bus=getattr(request.app.state, "bus", None),
+ capability_policy=getattr(
+ request.app.state,
+ "capability_policy",
+ None,
+ ),
+ rate_limiter=getattr(
+ request.app.state, "rate_limiter", None
+ ),
+ agent_id=agent_id,
interactive=True,
confirm_callback=lambda _prompt: True,
)
diff --git a/src/openjarvis/server/api_routes.py b/src/openjarvis/server/api_routes.py
index 0ae099c2..87b8cea1 100644
--- a/src/openjarvis/server/api_routes.py
+++ b/src/openjarvis/server/api_routes.py
@@ -64,9 +64,45 @@ class OptimizeRunRequest(BaseModel):
agents_router = APIRouter(prefix="/v1/agents", tags=["agents"])
+def _execute_agent_admin_tool(request: Request, tool: Any, params: Dict[str, Any]):
+ """Execute an agent lifecycle operation through server security gates."""
+ from openjarvis.security.runtime import execute_secured_tool
+
+ state = request.app.state
+ return execute_secured_tool(
+ tool,
+ params,
+ bus=getattr(state, "bus", None),
+ capability_policy=getattr(state, "capability_policy", None),
+ rate_limiter=getattr(state, "rate_limiter", None),
+ agent_id="server:api",
+ )
+
+
+def _raise_agent_tool_failure(result: Any, *, not_found: bool = False) -> None:
+ if result.success:
+ return
+ if "Capability '" in result.content and " denied " in result.content:
+ raise HTTPException(status_code=403, detail=result.content)
+ if result.content.startswith("Rate limit exceeded"):
+ raise HTTPException(status_code=429, detail=result.content)
+ raise HTTPException(status_code=404 if not_found else 400, detail=result.content)
+
+
@agents_router.get("")
async def list_agents(request: Request):
"""List available agent types and running agents."""
+ try:
+ from openjarvis.tools.agent_tools import AgentListTool
+
+ # Registry names and live agent metadata are administrative state,
+ # just like spawn/send/kill. Authorize before reading either source
+ # so default-deny and rate-limit policies cannot be bypassed by GET.
+ result = _execute_agent_admin_tool(request, AgentListTool(), {})
+ _raise_agent_tool_failure(result)
+ except ImportError:
+ raise HTTPException(status_code=501, detail="Agent tools not available")
+
registered = []
try:
import openjarvis.agents # noqa: F401 — side-effect registration
@@ -107,9 +143,8 @@ async def create_agent(req: AgentCreateRequest, request: Request):
params["tools"] = ",".join(req.tools)
if req.agent_id:
params["agent_id"] = req.agent_id
- result = tool.execute(**params)
- if not result.success:
- raise HTTPException(status_code=400, detail=result.content)
+ result = _execute_agent_admin_tool(request, tool, params)
+ _raise_agent_tool_failure(result)
return {
"status": "created",
"content": result.content,
@@ -126,9 +161,8 @@ async def kill_agent(agent_id: str, request: Request):
from openjarvis.tools.agent_tools import AgentKillTool
tool = AgentKillTool()
- result = tool.execute(agent_id=agent_id)
- if not result.success:
- raise HTTPException(status_code=404, detail=result.content)
+ result = _execute_agent_admin_tool(request, tool, {"agent_id": agent_id})
+ _raise_agent_tool_failure(result, not_found=True)
return {"status": "stopped", "agent_id": agent_id}
except ImportError:
raise HTTPException(status_code=501, detail="Agent tools not available")
@@ -141,9 +175,12 @@ async def message_agent(agent_id: str, req: AgentMessageRequest, request: Reques
from openjarvis.tools.agent_tools import AgentSendTool
tool = AgentSendTool()
- result = tool.execute(agent_id=agent_id, message=req.message)
- if not result.success:
- raise HTTPException(status_code=404, detail=result.content)
+ result = _execute_agent_admin_tool(
+ request,
+ tool,
+ {"agent_id": agent_id, "message": req.message},
+ )
+ _raise_agent_tool_failure(result, not_found=True)
return {"status": "sent", "content": result.content}
except ImportError:
raise HTTPException(status_code=501, detail="Agent tools not available")
diff --git a/src/openjarvis/server/app.py b/src/openjarvis/server/app.py
index 6c830c8f..ae14104e 100644
--- a/src/openjarvis/server/app.py
+++ b/src/openjarvis/server/app.py
@@ -91,6 +91,12 @@ def _restore_sendblue_bindings(app: FastAPI) -> None:
engine=engine,
model=model_name,
tools=tools,
+ bus=getattr(app.state, "bus", None),
+ capability_policy=getattr(
+ app.state, "capability_policy", None
+ ),
+ rate_limiter=getattr(app.state, "rate_limiter", None),
+ agent_id=agent_id,
)
bus = getattr(app.state, "bus", None)
@@ -161,6 +167,9 @@ def create_app(
agent_scheduler=None,
mcp_tools=None,
mcp_clients=None,
+ capability_policy=None,
+ rate_limiter=None,
+ audit_logger=None,
api_key: str = "",
webhook_config: dict | None = None,
cors_origins: list[str] | None = None,
@@ -182,6 +191,54 @@ def create_app(
config:
Optional JarvisConfig for other settings.
"""
+ original_engine = engine
+ security_enabled = config is not None and getattr(
+ getattr(config, "security", None), "enabled", False
+ )
+ if security_enabled:
+ if bus is None:
+ from openjarvis.core.events import EventBus
+
+ bus = EventBus(record_history=False)
+ if any(
+ primitive is None
+ for primitive in (capability_policy, rate_limiter, audit_logger)
+ ):
+ # Programmatic factory callers must receive the same config-driven
+ # enforcement as ``jarvis serve``. Explicitly injected primitives
+ # remain authoritative; only missing pieces are derived.
+ from openjarvis.security import setup_security
+
+ derived_security = setup_security(config, engine, bus)
+ engine = derived_security.engine
+ if capability_policy is None:
+ capability_policy = derived_security.capability_policy
+ if rate_limiter is None:
+ rate_limiter = derived_security.rate_limiter
+ if audit_logger is None:
+ audit_logger = derived_security.audit_logger
+
+ # A pre-built tool-using agent is part of the factory's remote execution
+ # surface too. Fill only missing executor fields so explicit per-agent
+ # wiring remains authoritative.
+ if agent is not None and getattr(agent, "_engine", None) is original_engine:
+ agent._engine = engine
+ from openjarvis.security.runtime import wire_agent_security
+
+ wire_agent_security(
+ agent,
+ bus=bus,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id=(
+ agent_name
+ or getattr(agent, "_runtime_agent_id", "")
+ or getattr(agent, "agent_id", "")
+ ),
+ overwrite=False,
+ synchronize_runtime_cache=True,
+ )
+
app = FastAPI(
title="OpenJarvis API",
description="OpenAI-compatible API server for OpenJarvis",
@@ -226,6 +283,13 @@ def create_app(
app.state.speech_backend = speech_backend
app.state.agent_manager = agent_manager
app.state.agent_scheduler = agent_scheduler
+ # Security primitives for the managed-agent HTTP/SSE routes
+ # (agent_manager_routes.py). Previously never passed here at all, so
+ # every managed agent reached over the network ran with no RBAC gate,
+ # no rate limiting, and no audit trail regardless of config.
+ app.state.capability_policy = capability_policy
+ app.state.rate_limiter = rate_limiter
+ app.state.audit_logger = audit_logger
app.state.mcp_tools = list(mcp_tools or [])
app.state._mcp_discovery_lock = threading.Lock()
app.state._mcp_clients_lock = threading.Lock()
diff --git a/src/openjarvis/server/webhook_routes.py b/src/openjarvis/server/webhook_routes.py
index fbfc103e..93f2b0ab 100644
--- a/src/openjarvis/server/webhook_routes.py
+++ b/src/openjarvis/server/webhook_routes.py
@@ -216,6 +216,14 @@ def create_webhook_router(
"",
),
tools=tools,
+ bus=getattr(request.app.state, "bus", None),
+ capability_policy=getattr(
+ request.app.state, "capability_policy", None
+ ),
+ rate_limiter=getattr(
+ request.app.state, "rate_limiter", None
+ ),
+ agent_id="server:webhook:twilio",
max_turns=5,
)
result = agent.run(body)
diff --git a/src/openjarvis/system/builder.py b/src/openjarvis/system/builder.py
index 0696ea5a..fa29151a 100644
--- a/src/openjarvis/system/builder.py
+++ b/src/openjarvis/system/builder.py
@@ -185,6 +185,7 @@ class SystemBuilder:
sec = setup_security(config, engine, bus)
engine = sec.engine
+ agent_name = self._agent_name or config.agent.default_agent
if telemetry_enabled:
from openjarvis.telemetry.instrumented_engine import (
@@ -210,8 +211,21 @@ class SystemBuilder:
model,
memory_backend,
channel_backend,
+ bus=bus,
+ capability_policy=sec.capability_policy,
+ rate_limiter=sec.rate_limiter,
+ )
+ tool_executor = (
+ ToolExecutor(
+ tool_list,
+ bus,
+ capability_policy=sec.capability_policy,
+ agent_id=agent_name,
+ rate_limiter=sec.rate_limiter,
+ )
+ if tool_list
+ else None
)
- tool_executor = ToolExecutor(tool_list, bus) if tool_list else None
skill_manager = None
skill_few_shot_examples: List[str] = []
@@ -236,12 +250,17 @@ class SystemBuilder:
)
tool_list.extend(skill_tools)
if tool_list:
- tool_executor = ToolExecutor(tool_list, bus)
+ tool_executor = ToolExecutor(
+ tool_list,
+ bus,
+ capability_policy=sec.capability_policy,
+ agent_id=agent_name,
+ rate_limiter=sec.rate_limiter,
+ )
skill_few_shot_examples = skill_manager.get_few_shot_examples()
except Exception as exc:
logger.warning("Failed to initialize skills: %s", exc)
- agent_name = self._agent_name or config.agent.default_agent
container_runner = self._setup_sandbox(config)
scheduler_store, task_scheduler = self._setup_scheduler(config, bus)
workflow_engine = self._setup_workflow(config, bus)
@@ -334,6 +353,7 @@ class SystemBuilder:
session_store=session_store,
capability_policy=capability_policy,
audit_logger=sec.audit_logger,
+ rate_limiter=sec.rate_limiter,
agent_manager=agent_manager,
agent_scheduler=agent_scheduler,
agent_executor=agent_executor,
@@ -442,12 +462,26 @@ class SystemBuilder:
return None
def _resolve_tools(
- self, config, engine, model, memory_backend, channel_backend=None
+ self,
+ config,
+ engine,
+ model,
+ memory_backend,
+ channel_backend=None,
+ *,
+ bus=None,
+ capability_policy=None,
+ rate_limiter=None,
):
"""Resolve tool instances via MCPServer (primary) + external MCP servers."""
from openjarvis.mcp.server import MCPServer
- internal_server = MCPServer()
+ internal_server = MCPServer(
+ bus=bus,
+ capability_policy=capability_policy,
+ rate_limiter=rate_limiter,
+ agent_id="system:mcp",
+ )
for tool in internal_server.get_tools():
self._inject_tool_deps(tool, engine, model, memory_backend, channel_backend)
diff --git a/src/openjarvis/system/bundles.py b/src/openjarvis/system/bundles.py
index f3d3583f..38b75fb6 100644
--- a/src/openjarvis/system/bundles.py
+++ b/src/openjarvis/system/bundles.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Any, Optional
if TYPE_CHECKING:
from openjarvis.agents._stubs import BaseAgent
@@ -28,6 +28,7 @@ class SecurityContext:
capability_policy: Optional[CapabilityPolicy] = None
audit_logger: Optional[AuditLogger] = None
boundary_guard: Optional[BoundaryGuard] = None
+ rate_limiter: Optional[Any] = None
@dataclass
diff --git a/src/openjarvis/system/core.py b/src/openjarvis/system/core.py
index e0d803f1..9134fdb5 100644
--- a/src/openjarvis/system/core.py
+++ b/src/openjarvis/system/core.py
@@ -89,6 +89,7 @@ class JarvisSystem:
# Keep newly added fields after every pre-existing positional field so
# older positional JarvisSystem(...) calls retain their original meaning.
mcp_tools: List[BaseTool] = field(default_factory=list)
+ rate_limiter: Optional[Any] = None
@property
def security(self) -> SecurityContext:
@@ -96,6 +97,7 @@ class JarvisSystem:
capability_policy=self.capability_policy,
audit_logger=self.audit_logger,
boundary_guard=self.boundary_guard,
+ rate_limiter=self.rate_limiter,
)
@property
diff --git a/src/openjarvis/system/orchestrator.py b/src/openjarvis/system/orchestrator.py
index 6b7073f5..90a0eb3d 100644
--- a/src/openjarvis/system/orchestrator.py
+++ b/src/openjarvis/system/orchestrator.py
@@ -158,13 +158,26 @@ class QueryOrchestrator:
if getattr(agent_cls, "accepts_tools", False):
agent_kwargs["tools"] = agent_tools
agent_kwargs["max_turns"] = s.config.agent.max_turns
+ agent_kwargs["agent_id"] = agent_name
+ if s.capability_policy is not None:
+ agent_kwargs["capability_policy"] = s.capability_policy
+ if getattr(s, "rate_limiter", None) is not None:
+ agent_kwargs["rate_limiter"] = s.rate_limiter
examples = getattr(s, "_skill_few_shot_examples", None)
if examples:
agent_kwargs["skill_few_shot_examples"] = examples
+ from openjarvis.security.runtime import agent_security_kwargs
+
+ agent_kwargs.update(
+ agent_security_kwargs(
+ agent_cls,
+ capability_policy=s.capability_policy,
+ rate_limiter=getattr(s, "rate_limiter", None),
+ agent_id=agent_name,
+ )
+ )
if system_prompt is not None:
agent_kwargs["system_prompt"] = system_prompt
- if s.capability_policy is not None:
- agent_kwargs["capability_policy"] = s.capability_policy
if operator_id is not None:
agent_kwargs["operator_id"] = operator_id
agent_kwargs["session_store"] = s.session_store
@@ -204,6 +217,16 @@ class QueryOrchestrator:
except TypeError:
ag = agent_cls()
+ from openjarvis.security.runtime import wire_agent_security
+
+ wire_agent_security(
+ ag,
+ bus=s.bus,
+ capability_policy=s.capability_policy,
+ rate_limiter=getattr(s, "rate_limiter", None),
+ agent_id=agent_name,
+ )
+
telemetry_events: List[Dict[str, Any]] = []
def _on_inference_end(event: Any) -> None:
diff --git a/src/openjarvis/system/protocols.py b/src/openjarvis/system/protocols.py
index 405bc5fa..c9a63f0c 100644
--- a/src/openjarvis/system/protocols.py
+++ b/src/openjarvis/system/protocols.py
@@ -32,6 +32,7 @@ class OrchestratorDeps(Protocol):
tools: List[BaseTool]
memory_backend: Optional[MemoryBackend]
capability_policy: Optional[CapabilityPolicy]
+ rate_limiter: Optional[Any]
session_store: Optional[SessionStore]
trace_store: Optional[TraceStore]
trace_collector: Optional[TraceCollector] # written by _run_agent
diff --git a/src/openjarvis/tools/_stubs.py b/src/openjarvis/tools/_stubs.py
index 38c619b9..54ae1d9e 100644
--- a/src/openjarvis/tools/_stubs.py
+++ b/src/openjarvis/tools/_stubs.py
@@ -198,6 +198,7 @@ class ToolExecutor:
capability_policy: Optional[Any] = None,
agent_id: str = "",
boundary_guard: Optional[Any] = None,
+ rate_limiter: Optional[Any] = None,
) -> None:
self._tools: Dict[str, BaseTool] = {t.spec.name: t for t in tools}
self._bus = bus
@@ -207,6 +208,7 @@ class ToolExecutor:
self._capability_policy = capability_policy
self._agent_id = agent_id
self._boundary_guard = boundary_guard
+ self._rate_limiter = rate_limiter
def execute(self, tool_call: ToolCall) -> ToolResult:
"""Parse arguments, dispatch to tool, measure latency, emit events."""
@@ -237,6 +239,31 @@ class ToolExecutor:
success=False,
)
+ # Rate limiting — checked before any other gate so a hammering
+ # agent/skill can't burn through boundary/capability/taint checks.
+ if self._rate_limiter is not None:
+ allowed, wait_seconds = self._rate_limiter.check(
+ f"{self._agent_id}:{tool_call.name}"
+ )
+ if not allowed:
+ if self._bus:
+ self._bus.publish(
+ EventType.RATE_LIMITED,
+ {
+ "agent_id": self._agent_id,
+ "tool": tool_call.name,
+ "wait_seconds": wait_seconds,
+ },
+ )
+ return ToolResult(
+ tool_name=tool_call.name,
+ content=(
+ f"Rate limit exceeded for tool '{tool_call.name}'."
+ f" Retry after {wait_seconds:.1f}s."
+ ),
+ success=False,
+ )
+
# Boundary guard: scan external tool arguments
if self._boundary_guard is not None and not getattr(tool, "is_local", True):
try:
@@ -259,9 +286,20 @@ class ToolExecutor:
success=False,
)
- # RBAC capability check
- if self._capability_policy and tool.spec.required_capabilities:
- for cap in tool.spec.required_capabilities:
+ # RBAC capability check. A built-in's canonical requirements are a
+ # security floor: a missing (or accidentally weakened) ToolSpec must
+ # not turn a privileged built-in into an unguarded tool.
+ required_capabilities = list(tool.spec.required_capabilities)
+ if self._capability_policy is not None:
+ from openjarvis.security.capabilities import canonical_tool_capabilities
+
+ for cap in canonical_tool_capabilities(tool):
+ cap_value = cap.value if hasattr(cap, "value") else cap
+ if cap_value not in required_capabilities:
+ required_capabilities.append(cap_value)
+
+ if self._capability_policy is not None:
+ for cap in required_capabilities:
if not self._capability_policy.check(
self._agent_id,
cap,
diff --git a/tests/agents/test_direct_operation_security.py b/tests/agents/test_direct_operation_security.py
new file mode 100644
index 00000000..e54a8513
--- /dev/null
+++ b/tests/agents/test_direct_operation_security.py
@@ -0,0 +1,106 @@
+"""Security gates for agents that execute outside ToolUsingAgent."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+import pytest
+
+from openjarvis.agents.claude_code import ClaudeCodeAgent
+from openjarvis.agents.hybrid.baseline_cloud import BaselineCloudAgent
+from openjarvis.agents.hybrid.mini_swe_agent import MiniSWEAgent
+from openjarvis.agents.opencode import OpenCodeAgent
+from openjarvis.agents.openhands import OpenHandsAgent
+from openjarvis.core.events import EventBus, EventType
+from openjarvis.security.capabilities import CapabilityPolicy
+
+
+class _RecordingLimiter:
+ def __init__(self) -> None:
+ self.keys: list[str] = []
+
+ def check(self, key: str):
+ self.keys.append(key)
+ return True, 0.0
+
+
+ ("agent_cls", "agent_id", "operation"),
+ [
+ (ClaudeCodeAgent, "restricted-claude", "agent_run"),
+ (OpenCodeAgent, "restricted-opencode", "agent_run"),
+ (OpenHandsAgent, "restricted-openhands", "agent_run"),
+ (MiniSWEAgent, "restricted-mini-swe", "hybrid_agent_run"),
+ ],
+)
+def test_registered_execution_agents_fail_closed_before_side_effects(
+ agent_cls, agent_id, operation
+):
+ policy = CapabilityPolicy(default_deny=True)
+ limiter = _RecordingLimiter()
+ bus = EventBus(record_history=True)
+ agent = agent_cls(
+ MagicMock(),
+ "test-model",
+ bus=bus,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ agent_id=agent_id,
+ )
+ paradigm = MagicMock(return_value=("should not run", {}))
+ if isinstance(agent, MiniSWEAgent):
+ agent._run_paradigm = paradigm
+
+ result = agent.run("perform workspace changes")
+
+ assert result.metadata["security_denied"] is True
+ assert "code:execute" in result.content
+ assert limiter.keys == [f"{agent_id}:{operation}"]
+ paradigm.assert_not_called()
+ denied = [
+ event
+ for event in bus.history
+ if event.event_type == EventType.CAPABILITY_DENIED
+ ]
+ assert denied[-1].data["agent_id"] == agent_id
+
+
+def test_mini_swe_explicit_grants_allow_registered_agent_run():
+ policy = CapabilityPolicy(default_deny=True)
+ for capability in ("code:execute", "file:read", "file:write"):
+ policy.grant("allowed-mini-swe", capability)
+ limiter = _RecordingLimiter()
+ agent = MiniSWEAgent(
+ MagicMock(),
+ "test-model",
+ capability_policy=policy,
+ rate_limiter=limiter,
+ agent_id="allowed-mini-swe",
+ )
+ agent._run_paradigm = MagicMock(return_value=("completed", {"turns": 1}))
+
+ result = agent.run("perform workspace changes")
+
+ assert result.content == "completed"
+ agent._run_paradigm.assert_called_once()
+ assert limiter.keys == ["allowed-mini-swe:hybrid_agent_run"]
+
+
+def test_hybrid_tavily_path_requires_network_before_search():
+ policy = CapabilityPolicy(default_deny=True)
+ limiter = _RecordingLimiter()
+ agent = BaselineCloudAgent(
+ MagicMock(),
+ "test-model",
+ cfg={"search_backend": "tavily"},
+ capability_policy=policy,
+ rate_limiter=limiter,
+ agent_id="restricted-hybrid",
+ )
+ agent._run_paradigm = MagicMock(return_value=("should not run", {}))
+
+ result = agent.run("research current facts")
+
+ assert "network:fetch" in result.content
+ agent._run_paradigm.assert_not_called()
+ assert limiter.keys == ["restricted-hybrid:hybrid_agent_run"]
diff --git a/tests/agents/test_executor_ephemeral.py b/tests/agents/test_executor_ephemeral.py
index 16062d1a..3902f10b 100644
--- a/tests/agents/test_executor_ephemeral.py
+++ b/tests/agents/test_executor_ephemeral.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from types import SimpleNamespace
from unittest.mock import MagicMock, patch
REGISTRY_PATH = "openjarvis.core.registry.AgentRegistry.get"
@@ -43,3 +44,75 @@ def test_run_ephemeral_passes_input():
input_text="Hello world",
)
mock_agent_instance.run.assert_called_once_with("Hello world")
+
+
+def test_run_ephemeral_resolves_tools_and_preserves_security():
+ from openjarvis.agents.executor import AgentExecutor
+ from openjarvis.agents.simple import SimpleAgent
+ from openjarvis.core.events import EventBus
+ from openjarvis.core.registry import AgentRegistry, ToolRegistry
+ from openjarvis.core.types import ToolResult
+ from openjarvis.security.capabilities import CapabilityPolicy
+ from openjarvis.tools._stubs import BaseTool, ToolSpec
+
+ class _FlushProbe(BaseTool):
+ calls = 0
+
+ @property
+ def spec(self):
+ return ToolSpec(
+ name="flush_probe",
+ description="persist session state",
+ required_capabilities=["memory:write"],
+ )
+
+ def execute(self, **params):
+ type(self).calls += 1
+ return ToolResult(tool_name="flush_probe", content="stored")
+
+ class _RecordingLimiter:
+ def __init__(self):
+ self.keys = []
+
+ def check(self, key):
+ self.keys.append(key)
+ return True, 0.0
+
+ engine = MagicMock()
+ engine.generate.side_effect = [
+ {
+ "content": "",
+ "tool_calls": [{"id": "flush", "name": "flush_probe", "arguments": "{}"}],
+ "finish_reason": "tool_calls",
+ },
+ {"content": "done", "finish_reason": "stop"},
+ ]
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "memory:write")
+ policy.deny("ephemeral:simple", "memory:write")
+ limiter = _RecordingLimiter()
+ system = SimpleNamespace(
+ engine=engine,
+ model="test-model",
+ capability_policy=policy,
+ rate_limiter=limiter,
+ )
+ AgentRegistry.register_value("simple", SimpleAgent)
+ ToolRegistry.register_value("flush_probe", _FlushProbe)
+ executor = AgentExecutor(
+ manager=MagicMock(),
+ event_bus=EventBus(record_history=True),
+ system=system,
+ )
+
+ result = executor.run_ephemeral(
+ agent_type="simple",
+ system_prompt="persist",
+ input_text="flush now",
+ tools=["flush_probe"],
+ )
+
+ assert len(result.tool_results) == 1
+ assert "memory:write" in result.tool_results[0].content
+ assert _FlushProbe.calls == 0
+ assert limiter.keys == ["ephemeral:simple:flush_probe"]
diff --git a/tests/agents/test_executor_tools.py b/tests/agents/test_executor_tools.py
index ad94ddcb..ea619351 100644
--- a/tests/agents/test_executor_tools.py
+++ b/tests/agents/test_executor_tools.py
@@ -15,7 +15,7 @@ from openjarvis.agents.manager import AgentManager
from openjarvis.agents.tool_resolver import ResolvedAgentTools
from openjarvis.connectors.store import KnowledgeStore
from openjarvis.core.config import MemoryFilesConfig, SystemPromptConfig
-from openjarvis.core.events import EventBus
+from openjarvis.core.events import EventBus, EventType
from openjarvis.core.registry import AgentRegistry, ToolRegistry
from openjarvis.core.types import Role, ToolResult
from openjarvis.tools._stubs import BaseTool, ToolSpec
@@ -87,6 +87,23 @@ class _ExecutorProbeTool(BaseTool):
return ToolResult(tool_name=self.tool_id, content="probe-result")
+class _PrivilegedExecutorProbeTool(BaseTool):
+ tool_id = "privileged_executor_probe"
+ calls = 0
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name=self.tool_id,
+ description="Managed-agent enforcement probe",
+ required_capabilities=["code:execute"],
+ )
+
+ def execute(self, **params) -> ToolResult:
+ type(self).calls += 1
+ return ToolResult(tool_name=self.tool_id, content="unsafe")
+
+
def _register_agent():
"""Re-register MonitorOperativeAgent (cleared by autouse fixture)."""
from openjarvis.agents.monitor_operative import MonitorOperativeAgent
@@ -247,6 +264,79 @@ def test_executor_uses_tool_loop_for_non_tool_agent_with_configured_tools(tmp_pa
manager.close()
+def test_executor_enforces_managed_agent_capability_denial(tmp_path):
+ """Scheduled/immediate agents cannot bypass the system security policy."""
+
+ AgentRegistry.register_value("non_tool_probe", _NonToolAgent)
+ ToolRegistry.register_value(
+ _PrivilegedExecutorProbeTool.tool_id,
+ _PrivilegedExecutorProbeTool,
+ )
+ _PrivilegedExecutorProbeTool.calls = 0
+
+ engine = FakeEngine(
+ [
+ {
+ "tool_calls": [
+ {
+ "id": "call-managed-denied",
+ "name": _PrivilegedExecutorProbeTool.tool_id,
+ "arguments": "{}",
+ }
+ ]
+ },
+ {"content": "request safely refused"},
+ ]
+ )
+ system = SimpleNamespace(
+ engine=engine,
+ model="test-model",
+ memory_backend=None,
+ channel_backend=None,
+ tool_executor=None,
+ tools=[],
+ mcp_tools=[],
+ _mcp_clients=[],
+ config=None,
+ session_store=None,
+ capability_policy=None,
+ rate_limiter=None,
+ )
+ manager = AgentManager(db_path=str(tmp_path / "agents.db"))
+ agent = manager.create_agent(
+ "managed deny probe",
+ agent_type="non_tool_probe",
+ config={
+ "model": "test-model",
+ "tools": [_PrivilegedExecutorProbeTool.tool_id],
+ "instruction": "Attempt the privileged probe.",
+ },
+ )
+
+ class _DenyPolicy:
+ def check(self, agent_id, capability, resource=""):
+ assert agent_id == agent["id"]
+ assert capability == "code:execute"
+ return False
+
+ system.capability_policy = _DenyPolicy()
+ bus = EventBus(record_history=True)
+
+ try:
+ AgentExecutor(manager, bus, system=system).execute_tick(agent["id"])
+
+ assert _PrivilegedExecutorProbeTool.calls == 0
+ denied = [
+ event
+ for event in bus.history
+ if event.event_type == EventType.CAPABILITY_DENIED
+ ]
+ assert len(denied) == 1
+ assert denied[0].data["agent_id"] == agent["id"]
+ finally:
+ manager.close()
+
+
def test_simple_agent_uses_global_mcp_tools_without_native_tool_config(tmp_path):
"""Fallback-compatible simple agents preserve SSE/global-MCP parity."""
diff --git a/tests/agents/test_hybrid_provider_search_security.py b/tests/agents/test_hybrid_provider_search_security.py
new file mode 100644
index 00000000..19831348
--- /dev/null
+++ b/tests/agents/test_hybrid_provider_search_security.py
@@ -0,0 +1,249 @@
+"""Provider-search security regressions across hybrid agents."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+import pytest
+
+import openjarvis.agents.hybrid.conductor as conductor_module
+import openjarvis.agents.hybrid.minions as minions_module
+from openjarvis.agents._stubs import AgentContext
+from openjarvis.agents.hybrid.advisors import AdvisorsAgent
+from openjarvis.agents.hybrid.conductor import ConductorAgent
+from openjarvis.agents.hybrid.minions import MinionsAgent
+from openjarvis.core.events import EventBus, EventType
+from openjarvis.security.capabilities import CapabilityPolicy
+
+
+class _Limiter:
+ def __init__(self) -> None:
+ self.keys: list[str] = []
+
+ def check(self, key: str):
+ self.keys.append(key)
+ return True, 0.0
+
+
+def _policy(agent_id: str, *, network: bool = False) -> CapabilityPolicy:
+ policy = CapabilityPolicy(default_deny=True)
+ for capability in ("code:execute", "file:read", "file:write"):
+ policy.grant(agent_id, capability)
+ if network:
+ policy.grant(agent_id, "network:fetch")
+ return policy
+
+
+ ("agent_cls", "agent_id"),
+ [(AdvisorsAgent, "advisors-sec"), (ConductorAgent, "conductor-sec")],
+)
+def test_enabled_provider_search_is_required_before_hybrid_run(agent_cls, agent_id):
+ limiter = _Limiter()
+ agent = agent_cls(
+ MagicMock(),
+ "cloud-model",
+ cfg={"web_search": {"enabled": True}},
+ capability_policy=_policy(agent_id),
+ rate_limiter=limiter,
+ agent_id=agent_id,
+ )
+ agent._run_paradigm = MagicMock(return_value=("should not run", {}))
+
+ result = agent.run("research")
+
+ assert "network:fetch" in result.content
+ agent._run_paradigm.assert_not_called()
+ assert limiter.keys == [f"{agent_id}:hybrid_agent_run"]
+
+
+def test_minions_legacy_prefetch_is_required_before_hybrid_run():
+ limiter = _Limiter()
+ agent = MinionsAgent(
+ MagicMock(),
+ "cloud-model",
+ capability_policy=_policy("minions-sec"),
+ rate_limiter=limiter,
+ agent_id="minions-sec",
+ )
+ agent._run_paradigm = MagicMock(return_value=("should not run", {}))
+ context = AgentContext(metadata={"task": {"question": "recent facts"}})
+
+ result = agent.run("research", context)
+
+ assert "network:fetch" in result.content
+ agent._run_paradigm.assert_not_called()
+ assert limiter.keys == ["minions-sec:hybrid_agent_run"]
+
+
+def test_advisors_provider_denial_prevents_provider_search(monkeypatch):
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = AdvisorsAgent(
+ MagicMock(),
+ "cloud-model",
+ cfg={"web_search": {"enabled": True}},
+ bus=bus,
+ capability_policy=_policy("advisors-sec"),
+ rate_limiter=limiter,
+ agent_id="advisors-sec",
+ )
+ provider_search = MagicMock()
+ monkeypatch.setattr(agent, "_call_anthropic_agent", provider_search)
+
+ result = agent._executor_search(
+ user="research",
+ system="system",
+ max_tokens=100,
+ ws_max_uses=2,
+ max_turns=2,
+ )
+
+ assert "network:fetch" in result[0]
+ provider_search.assert_not_called()
+ assert limiter.keys == ["advisors-sec:advisors_provider_search"]
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data["tool"] == "advisors_provider_search"
+ for event in bus.history
+ )
+
+
+def test_advisors_provider_positive_grant_executes(monkeypatch):
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = AdvisorsAgent(
+ MagicMock(),
+ "cloud-model",
+ cfg={"web_search": {"enabled": True}},
+ bus=bus,
+ capability_policy=_policy("advisors-sec", network=True),
+ rate_limiter=limiter,
+ agent_id="advisors-sec",
+ )
+ provider_search = MagicMock(return_value=("findings", 1, 2, 1, 1))
+ monkeypatch.setattr(agent, "_call_anthropic_agent", provider_search)
+
+ result = agent._executor_search(
+ user="research",
+ system="system",
+ max_tokens=100,
+ ws_max_uses=2,
+ max_turns=2,
+ )
+
+ assert result[0] == "findings"
+ provider_search.assert_called_once()
+ assert limiter.keys == ["advisors-sec:advisors_provider_search"]
+
+
+def test_conductor_provider_denial_prevents_worker_search(monkeypatch):
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = ConductorAgent(
+ MagicMock(),
+ "cloud-model",
+ bus=bus,
+ capability_policy=_policy("conductor-sec"),
+ rate_limiter=limiter,
+ agent_id="conductor-sec",
+ )
+ raw_worker = MagicMock()
+ monkeypatch.setattr(conductor_module, "_call_worker", raw_worker)
+
+ result = agent._call_worker_secured(
+ {"name": "worker", "endpoint": "anthropic", "model": "cloud-model"},
+ "research",
+ {},
+ web_search_tool={"type": "web_search"},
+ )
+
+ assert "network:fetch" in result[0]
+ raw_worker.assert_not_called()
+ assert limiter.keys == ["conductor-sec:conductor_provider_search"]
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data["tool"] == "conductor_provider_search"
+ for event in bus.history
+ )
+
+
+def test_conductor_provider_positive_grant_executes_worker(monkeypatch):
+ limiter = _Limiter()
+ agent = ConductorAgent(
+ MagicMock(),
+ "cloud-model",
+ capability_policy=_policy("conductor-sec", network=True),
+ rate_limiter=limiter,
+ agent_id="conductor-sec",
+ )
+ expected = ("findings", 1, 2, False, 1, 0.0)
+ raw_worker = MagicMock(return_value=expected)
+ monkeypatch.setattr(conductor_module, "_call_worker", raw_worker)
+
+ result = agent._call_worker_secured(
+ {"name": "worker", "endpoint": "anthropic", "model": "cloud-model"},
+ "research",
+ {},
+ web_search_tool={"type": "web_search"},
+ )
+
+ assert result == expected
+ raw_worker.assert_called_once()
+ assert limiter.keys == ["conductor-sec:conductor_provider_search"]
+
+
+def test_minions_provider_denial_prevents_prefetch(monkeypatch):
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = MinionsAgent(
+ MagicMock(),
+ "cloud-model",
+ bus=bus,
+ capability_policy=_policy("minions-sec"),
+ rate_limiter=limiter,
+ agent_id="minions-sec",
+ )
+ raw_prefetch = MagicMock()
+ monkeypatch.setattr(minions_module, "_prefetch_context", raw_prefetch)
+
+ result = agent._prefetch_context_secured(
+ "recent facts",
+ max_uses=2,
+ search_backend="provider",
+ tavily_max_results=3,
+ )
+
+ assert "network:fetch" in result["error"]
+ raw_prefetch.assert_not_called()
+ assert limiter.keys == ["minions-sec:minions_provider_prefetch"]
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data["tool"] == "minions_provider_prefetch"
+ for event in bus.history
+ )
+
+
+def test_minions_provider_positive_grant_executes_prefetch(monkeypatch):
+ limiter = _Limiter()
+ agent = MinionsAgent(
+ MagicMock(),
+ "cloud-model",
+ capability_policy=_policy("minions-sec", network=True),
+ rate_limiter=limiter,
+ agent_id="minions-sec",
+ )
+ expected = {"text": "findings", "tokens": 3, "cost_usd": 0.1, "n_searches": 1}
+ raw_prefetch = MagicMock(return_value=expected)
+ monkeypatch.setattr(minions_module, "_prefetch_context", raw_prefetch)
+
+ result = agent._prefetch_context_secured(
+ "recent facts",
+ max_uses=2,
+ search_backend="provider",
+ tavily_max_results=3,
+ )
+
+ assert result == expected
+ raw_prefetch.assert_called_once()
+ assert limiter.keys == ["minions-sec:minions_provider_prefetch"]
diff --git a/tests/agents/test_native_openhands.py b/tests/agents/test_native_openhands.py
index 221f8bfc..bf370ade 100644
--- a/tests/agents/test_native_openhands.py
+++ b/tests/agents/test_native_openhands.py
@@ -542,7 +542,8 @@ class TestTruncation:
class TestUrlExpansion:
def test_no_url_returns_false(self):
- text, expanded = NativeOpenHandsAgent._expand_urls("What is 2+2?")
+ agent = NativeOpenHandsAgent(MagicMock(), "test-model")
+ text, expanded = agent._expand_urls("What is 2+2?")
assert text == "What is 2+2?"
assert expanded is False
@@ -555,9 +556,8 @@ class TestUrlExpansion:
mock_resp.raise_for_status = MagicMock()
monkeypatch.setattr(httpx, "get", MagicMock(return_value=mock_resp))
- text, expanded = NativeOpenHandsAgent._expand_urls(
- "Summarize: https://example.com/article"
- )
+ agent = NativeOpenHandsAgent(MagicMock(), "test-model")
+ text, expanded = agent._expand_urls("Summarize: https://example.com/article")
assert expanded is True
assert "Page content" in text
assert "Content from" in text
@@ -570,10 +570,54 @@ class TestUrlExpansion:
"get",
MagicMock(side_effect=Exception("Connection error")),
)
- text, expanded = NativeOpenHandsAgent._expand_urls(
- "Read https://example.com/broken"
+ agent = NativeOpenHandsAgent(MagicMock(), "test-model")
+ text, expanded = agent._expand_urls("Read https://example.com/broken")
+ assert expanded is False
+
+ def test_url_prefetch_uses_network_policy_rate_and_runtime_identity(
+ self, monkeypatch
+ ):
+ import httpx
+
+ from openjarvis.core.events import EventBus, EventType
+ from openjarvis.security.capabilities import CapabilityPolicy
+
+ class _RecordingLimiter:
+ def __init__(self):
+ self.keys = []
+
+ def check(self, key):
+ self.keys.append(key)
+ return True, 0.0
+
+ fetch = MagicMock()
+ monkeypatch.setattr(httpx, "get", fetch)
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "network:fetch")
+ policy.deny("restricted-native", "network:fetch")
+ limiter = _RecordingLimiter()
+ bus = EventBus(record_history=True)
+ agent = NativeOpenHandsAgent(
+ MagicMock(),
+ "test-model",
+ bus=bus,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ agent_id="restricted-native",
)
+
+ text, expanded = agent._expand_urls("Read https://example.com/private")
+
+ assert text == "Read https://example.com/private"
assert expanded is False
+ fetch.assert_not_called()
+ assert limiter.keys == ["restricted-native:web_search"]
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data["agent_id"] == "restricted-native"
+ and event.data["capability"] == "network:fetch"
+ for event in bus.history
+ )
def test_url_expanded_uses_direct_path(self, monkeypatch):
"""When URL is expanded, agent bypasses tool loop."""
diff --git a/tests/agents/test_rlm.py b/tests/agents/test_rlm.py
index 059aa062..13ae8230 100644
--- a/tests/agents/test_rlm.py
+++ b/tests/agents/test_rlm.py
@@ -179,6 +179,34 @@ class TestRLMDirectAnswer:
assert result.turns == 1
assert result.tool_results == []
+ def test_default_deny_blocks_agent_before_generated_code(self):
+ from openjarvis.security.capabilities import CapabilityPolicy
+
+ class _RecordingLimiter:
+ def __init__(self):
+ self.keys = []
+
+ def check(self, key):
+ self.keys.append(key)
+ return True, 0.0
+
+ engine = _make_engine_with_code("sentinel = 42")
+ limiter = _RecordingLimiter()
+ agent = RLMAgent(
+ engine,
+ "test-model",
+ capability_policy=CapabilityPolicy(default_deny=True),
+ rate_limiter=limiter,
+ agent_id="restricted-rlm",
+ )
+
+ result = agent.run("execute generated code")
+
+ assert result.metadata["security_denied"] is True
+ assert "code:execute" in result.content
+ engine.generate.assert_not_called()
+ assert limiter.keys == ["restricted-rlm:agent_run"]
+
class TestRLMFinalTermination:
def test_final_terminates(self):
diff --git a/tests/agents/test_skillorchestra_security.py b/tests/agents/test_skillorchestra_security.py
new file mode 100644
index 00000000..8c7190f6
--- /dev/null
+++ b/tests/agents/test_skillorchestra_security.py
@@ -0,0 +1,319 @@
+"""Security regressions for SkillOrchestra direct QA operations."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+from openjarvis.agents.hybrid.skillorchestra.agent import SkillOrchestraAgent
+from openjarvis.agents.hybrid.skillorchestra.pool import ModelSpec
+from openjarvis.agents.hybrid.skillorchestra.tools import run_code, run_search
+from openjarvis.core.events import EventBus, EventType
+from openjarvis.security.capabilities import CapabilityPolicy
+
+
+class _Limiter:
+ def __init__(self, denied_key: str = "") -> None:
+ self.denied_key = denied_key
+ self.keys: list[str] = []
+
+ def check(self, key: str):
+ self.keys.append(key)
+ return key != self.denied_key, 3.0 if key == self.denied_key else 0.0
+
+
+def _agent(policy, limiter, bus, agent_id="skill-runtime"):
+ return SkillOrchestraAgent(
+ MagicMock(),
+ "cloud-model",
+ bus=bus,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ agent_id=agent_id,
+ )
+
+
+def _grant_local_execution(policy, agent_id="skill-runtime"):
+ for capability in ("code:execute", "file:read", "file:write"):
+ policy.grant(agent_id, capability)
+
+
+def test_enhance_reasoning_denial_prevents_python_subprocess(monkeypatch):
+ from openjarvis.agents.hybrid.skillorchestra import tools as tools_module
+
+ policy = CapabilityPolicy(default_deny=True)
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent(policy, limiter, bus)
+ call_alias = MagicMock()
+ subprocess_run = MagicMock()
+ monkeypatch.setattr(tools_module, "call_alias", call_alias)
+ monkeypatch.setattr(tools_module.subprocess, "run", subprocess_run)
+
+ result = run_code(
+ agent,
+ ModelSpec("reasoner-1", "model", "anthropic", "cloud"),
+ context_str="context",
+ problem="problem",
+ )
+
+ assert "code:execute" in result["exec_result"]
+ call_alias.assert_not_called()
+ subprocess_run.assert_not_called()
+ assert limiter.keys == ["skill-runtime:skillorchestra_code"]
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data
+ == {
+ "agent_id": "skill-runtime",
+ "capability": "code:execute",
+ "tool": "skillorchestra_code",
+ }
+ for event in bus.history
+ )
+
+
+def test_enhance_reasoning_requires_tempfile_capabilities(monkeypatch):
+ from openjarvis.agents.hybrid.skillorchestra import tools as tools_module
+
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("skill-runtime", "code:execute")
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent(policy, limiter, bus)
+ call_alias = MagicMock()
+ subprocess_run = MagicMock()
+ monkeypatch.setattr(tools_module, "call_alias", call_alias)
+ monkeypatch.setattr(tools_module.subprocess, "run", subprocess_run)
+
+ result = run_code(
+ agent,
+ ModelSpec("reasoner-1", "model", "anthropic", "cloud"),
+ context_str="context",
+ problem="problem",
+ )
+
+ assert "file:read" in result["exec_result"]
+ call_alias.assert_not_called()
+ subprocess_run.assert_not_called()
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data["capability"] == "file:read"
+ for event in bus.history
+ )
+
+
+def test_custom_retriever_rate_limit_prevents_http_post(monkeypatch):
+ import requests
+
+ from openjarvis.agents.hybrid.skillorchestra import tools as tools_module
+
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("skill-runtime", "network:fetch")
+ denied_key = "skill-runtime:skillorchestra_retriever"
+ limiter = _Limiter(denied_key)
+ bus = EventBus(record_history=True)
+ agent = _agent(policy, limiter, bus)
+ monkeypatch.setattr(
+ tools_module,
+ "call_alias",
+ MagicMock(return_value=("<query>long enough query</query>", 1, 1, 0.0)),
+ )
+ post = MagicMock()
+ monkeypatch.setattr(requests, "post", post)
+
+ result = run_search(
+ agent,
+ ModelSpec("search-1", "model", "anthropic", "cloud"),
+ context_str="context",
+ problem="problem",
+ retriever_url="https://retriever.example",
+ )
+
+ assert "Rate limit exceeded" in result["search_results_data"][0]
+ post.assert_not_called()
+ assert limiter.keys == [denied_key]
+ assert any(
+ event.event_type == EventType.RATE_LIMITED
+ and event.data["agent_id"] == "skill-runtime"
+ and event.data["tool"] == "skillorchestra_retriever"
+ for event in bus.history
+ )
+
+
+def test_default_provider_search_denial_prevents_provider_call(monkeypatch):
+ from openjarvis.agents.hybrid.skillorchestra import tools as tools_module
+
+ policy = CapabilityPolicy(default_deny=True)
+ _grant_local_execution(policy)
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent(policy, limiter, bus)
+ monkeypatch.setattr(
+ tools_module,
+ "call_alias",
+ MagicMock(return_value=("<query>long enough query</query>", 1, 1, 0.0)),
+ )
+ provider_search = MagicMock()
+ monkeypatch.setattr(agent, "_call_anthropic_agent", provider_search)
+
+ result = run_search(
+ agent,
+ ModelSpec("search-1", "model", "anthropic", "cloud"),
+ context_str="context",
+ problem="problem",
+ )
+
+ assert "network:fetch" in result["search_results_data"][0]
+ provider_search.assert_not_called()
+ assert limiter.keys == ["skill-runtime:skillorchestra_provider_search"]
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data
+ == {
+ "agent_id": "skill-runtime",
+ "capability": "network:fetch",
+ "tool": "skillorchestra_provider_search",
+ }
+ for event in bus.history
+ )
+
+
+def test_tavily_search_denial_prevents_fetch(monkeypatch):
+ from openjarvis.agents.hybrid.skillorchestra import tools as tools_module
+
+ policy = CapabilityPolicy(default_deny=True)
+ _grant_local_execution(policy)
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent(policy, limiter, bus)
+ monkeypatch.setattr(
+ tools_module,
+ "call_alias",
+ MagicMock(return_value=("<query>long enough query</query>", 1, 1, 0.0)),
+ )
+ tavily = MagicMock()
+ monkeypatch.setattr(tools_module, "tavily_search_context", tavily)
+
+ result = run_search(
+ agent,
+ ModelSpec("search-1", "model", "anthropic", "cloud"),
+ context_str="context",
+ problem="problem",
+ search_backend="tavily",
+ )
+
+ assert "network:fetch" in result["search_results_data"][0]
+ tavily.assert_not_called()
+ assert limiter.keys == ["skill-runtime:skillorchestra_tavily"]
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data["tool"] == "skillorchestra_tavily"
+ for event in bus.history
+ )
+
+
+def test_provider_search_executes_with_positive_network_grant(monkeypatch):
+ from openjarvis.agents.hybrid.skillorchestra import tools as tools_module
+
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("skill-runtime", "network:fetch")
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent(policy, limiter, bus)
+ monkeypatch.setattr(
+ tools_module,
+ "call_alias",
+ MagicMock(return_value=("<query>long enough query</query>", 1, 1, 0.0)),
+ )
+ provider_search = MagicMock(return_value=("provider findings", 2, 3, 1, 1))
+ monkeypatch.setattr(agent, "_call_anthropic_agent", provider_search)
+
+ result = run_search(
+ agent,
+ ModelSpec("search-1", "model", "anthropic", "cloud"),
+ context_str="context",
+ problem="problem",
+ )
+
+ provider_search.assert_called_once()
+ assert result["search_results_data"] == ["provider findings"]
+ assert result["web_search_uses"] == 1
+ assert limiter.keys == ["skill-runtime:skillorchestra_provider_search"]
+ assert any(
+ event.event_type == EventType.TOOL_CALL_START
+ and event.data["tool"] == "skillorchestra_provider_search"
+ for event in bus.history
+ )
+
+
+def test_tavily_search_executes_with_positive_network_grant(monkeypatch):
+ from openjarvis.agents.hybrid.skillorchestra import tools as tools_module
+
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("skill-runtime", "network:fetch")
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent(policy, limiter, bus)
+ monkeypatch.setattr(
+ tools_module,
+ "call_alias",
+ MagicMock(return_value=("<query>long enough query</query>", 1, 1, 0.0)),
+ )
+ tavily = MagicMock(
+ return_value={"text": "tavily findings", "n_searches": 1, "cost_usd": 0.01}
+ )
+ monkeypatch.setattr(tools_module, "tavily_search_context", tavily)
+
+ result = run_search(
+ agent,
+ ModelSpec("search-1", "model", "anthropic", "cloud"),
+ context_str="context",
+ problem="problem",
+ search_backend="tavily",
+ )
+
+ tavily.assert_called_once_with("long enough query", max_results=5)
+ assert result["search_results_data"] == ["tavily findings"]
+ assert result["web_search_uses"] == 1
+ assert limiter.keys == ["skill-runtime:skillorchestra_tavily"]
+
+
+def test_retriever_configuration_is_derived_before_agent_run():
+ policy = CapabilityPolicy(default_deny=True)
+ _grant_local_execution(policy, "restricted-skill")
+ limiter = _Limiter()
+ agent = SkillOrchestraAgent(
+ MagicMock(),
+ "cloud-model",
+ cfg={"retriever_url": "https://retriever.example"},
+ capability_policy=policy,
+ rate_limiter=limiter,
+ agent_id="restricted-skill",
+ )
+ agent._run_paradigm = MagicMock(return_value=("should not run", {}))
+
+ result = agent.run("research")
+
+ assert "network:fetch" in result.content
+ agent._run_paradigm.assert_not_called()
+ assert limiter.keys == ["restricted-skill:hybrid_agent_run"]
+
+
+def test_default_provider_search_is_derived_before_agent_run():
+ policy = CapabilityPolicy(default_deny=True)
+ _grant_local_execution(policy, "restricted-skill")
+ limiter = _Limiter()
+ agent = SkillOrchestraAgent(
+ MagicMock(),
+ "cloud-model",
+ capability_policy=policy,
+ rate_limiter=limiter,
+ agent_id="restricted-skill",
+ )
+ agent._run_paradigm = MagicMock(return_value=("should not run", {}))
+
+ result = agent.run("research")
+
+ assert "network:fetch" in result.content
+ agent._run_paradigm.assert_not_called()
+ assert limiter.keys == ["restricted-skill:hybrid_agent_run"]
diff --git a/tests/agents/test_toolorchestra_security.py b/tests/agents/test_toolorchestra_security.py
new file mode 100644
index 00000000..36910f94
--- /dev/null
+++ b/tests/agents/test_toolorchestra_security.py
@@ -0,0 +1,186 @@
+"""Security regressions for ToolOrchestra worker/action dispatch."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import openjarvis.agents.hybrid.toolorchestra as toolorchestra_module
+from openjarvis.agents.hybrid.toolorchestra import ToolOrchestraAgent
+from openjarvis.core.events import EventBus, EventType
+from openjarvis.security.capabilities import CapabilityPolicy
+
+
+class _Limiter:
+ def __init__(self) -> None:
+ self.keys: list[str] = []
+
+ def check(self, key: str):
+ self.keys.append(key)
+ return True, 0.0
+
+
+def _agent(cfg, policy, limiter, bus, agent_id="tool-runtime"):
+ agent = ToolOrchestraAgent(
+ MagicMock(),
+ "claude-opus-4-7",
+ cfg=cfg,
+ bus=bus,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ agent_id=agent_id,
+ )
+ agent._run_paradigm = MagicMock(return_value=("should not run", {}))
+ return agent
+
+
+def _assert_denied(agent, bus, capability):
+ result = agent.run("research")
+
+ assert capability in result.content
+ agent._run_paradigm.assert_not_called()
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data
+ == {
+ "agent_id": "tool-runtime",
+ "capability": capability,
+ "tool": "hybrid_agent_run",
+ }
+ for event in bus.history
+ )
+
+
+def test_default_hosted_search_pool_requires_network_capability():
+ policy = CapabilityPolicy(default_deny=True)
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent({}, policy, limiter, bus)
+
+ _assert_denied(agent, bus, "network:fetch")
+
+ assert limiter.keys == ["tool-runtime:hybrid_agent_run"]
+
+
+def test_custom_tavily_worker_requires_network_even_with_provider_backend():
+ policy = CapabilityPolicy(default_deny=True)
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ cfg = {
+ "search_backend": "provider",
+ "worker_pool": [
+ {"id": 0, "name": "search", "type": "tavily-search"},
+ {
+ "id": 1,
+ "name": "solver",
+ "type": "anthropic",
+ "model": "claude-opus-4-7",
+ },
+ ],
+ }
+ agent = _agent(cfg, policy, limiter, bus)
+
+ _assert_denied(agent, bus, "network:fetch")
+
+ assert limiter.keys == ["tool-runtime:hybrid_agent_run"]
+
+
+def test_rl_paper_pool_requires_code_after_network_is_granted():
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("tool-runtime", "network:fetch")
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent(
+ {"orchestrator_mode": "rl", "pool": "paper"},
+ policy,
+ limiter,
+ bus,
+ )
+
+ _assert_denied(agent, bus, "code:execute")
+
+ assert limiter.keys == ["tool-runtime:hybrid_agent_run"]
+
+
+def test_selected_search_worker_is_gated_again_at_dispatch(monkeypatch):
+ policy = CapabilityPolicy(default_deny=True)
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent({}, policy, limiter, bus)
+ raw_dispatch = MagicMock()
+ monkeypatch.setattr(toolorchestra_module, "_call_worker", raw_dispatch)
+
+ result = agent._call_worker_secured(
+ {
+ "name": "web-search",
+ "type": "anthropic-web-search",
+ "model": "claude-haiku-4-5",
+ },
+ "query",
+ {},
+ )
+
+ assert "network:fetch" in result[0]
+ raw_dispatch.assert_not_called()
+ assert limiter.keys == ["tool-runtime:toolorchestra_worker"]
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data["tool"] == "toolorchestra_worker"
+ and event.data["capability"] == "network:fetch"
+ for event in bus.history
+ )
+
+
+def test_paper_python_is_gated_immediately_before_modal(monkeypatch):
+ policy = CapabilityPolicy(default_deny=True)
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent(
+ {"orchestrator_mode": "rl", "pool": "paper"},
+ policy,
+ limiter,
+ bus,
+ )
+ raw_modal = MagicMock()
+ monkeypatch.setattr(toolorchestra_module, "_call_modal_python", raw_modal)
+
+ output, returncode = agent._call_modal_python_secured("print(42)", timeout_s=3)
+
+ assert "code:execute" in output
+ assert returncode == -1
+ raw_modal.assert_not_called()
+ assert limiter.keys == ["tool-runtime:toolorchestra_modal_python"]
+
+
+def test_swe_worker_requires_file_caps_before_local_execution(monkeypatch):
+ policy = CapabilityPolicy(default_deny=True)
+ for capability in ("code:execute", "file:read"):
+ policy.grant("tool-runtime", capability)
+ limiter = _Limiter()
+ bus = EventBus(record_history=True)
+ agent = _agent({}, policy, limiter, bus)
+ raw_swe_dispatch = MagicMock()
+ monkeypatch.setattr(toolorchestra_module, "_swe_call_worker", raw_swe_dispatch)
+
+ result = agent._swe_call_worker_secured(
+ {
+ "name": "local-coder",
+ "type": "vllm",
+ "model": "local-model",
+ },
+ "solve",
+ {},
+ {"problem_statement": "fix it"},
+ Path("/tmp/worktree-probe"),
+ 1,
+ )
+
+ assert "file:write" in result[0]
+ raw_swe_dispatch.assert_not_called()
+ assert limiter.keys == ["tool-runtime:toolorchestra_swe_worker"]
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data["tool"] == "toolorchestra_swe_worker"
+ and event.data["capability"] == "file:write"
+ for event in bus.history
+ )
diff --git a/tests/cli/test_ask_router.py b/tests/cli/test_ask_router.py
index ddbae1e4..bd6cf1a5 100644
--- a/tests/cli/test_ask_router.py
+++ b/tests/cli/test_ask_router.py
@@ -8,6 +8,7 @@ from unittest import mock
from click.testing import CliRunner
from openjarvis.cli import cli
+from openjarvis.core.config import JarvisConfig
_ask_mod = importlib.import_module("openjarvis.cli.ask")
@@ -102,6 +103,7 @@ class TestAskModelResolution:
mock.patch.object(
_ask_mod,
"load_config",
+ return_value=JarvisConfig(),
) as mock_config,
):
cfg = mock_config.return_value
@@ -113,7 +115,8 @@ class TestAskModelResolution:
cfg.agent.context_from_memory = False
cfg.agent.default_agent = ""
result = CliRunner().invoke(cli, ["ask", "Hello"])
- assert result.exit_code == 0
+ assert result.exit_code == 0, result.output
+ assert engine.generate.call_args.kwargs["model"] == "test-model"
def test_fallback_to_fallback_model(self) -> None:
"""When default_model is empty and no engine models, uses fallback_model."""
@@ -134,6 +137,7 @@ class TestAskModelResolution:
mock.patch.object(
_ask_mod,
"load_config",
+ return_value=JarvisConfig(),
) as mock_config,
):
cfg = mock_config.return_value
@@ -145,4 +149,5 @@ class TestAskModelResolution:
cfg.agent.context_from_memory = False
cfg.agent.default_agent = ""
result = CliRunner().invoke(cli, ["ask", "Hello"])
- assert result.exit_code == 0
+ assert result.exit_code == 0, result.output
+ assert engine.generate.call_args.kwargs["model"] == "fallback-model"
diff --git a/tests/cli/test_chat_cmd.py b/tests/cli/test_chat_cmd.py
index ae4a9c3f..458d6803 100644
--- a/tests/cli/test_chat_cmd.py
+++ b/tests/cli/test_chat_cmd.py
@@ -44,6 +44,7 @@ class _DangerousChatTool(BaseTool):
name="dangerous_chat",
description="Confirmation-gated chat tool.",
requires_confirmation=True,
+ required_capabilities=["code:execute"],
)
def execute(self, **params) -> ToolResult:
@@ -659,3 +660,61 @@ class TestChatAgents:
assert result.exit_code == 0
assert "Confirm:" in result.output
assert "chat executed!" in result.output
+
+ def test_tool_agent_uses_configured_policy_rate_and_identity(self) -> None:
+ from openjarvis.security import SecurityContext
+ from openjarvis.security.capabilities import CapabilityPolicy
+
+ class _RecordingLimiter:
+ def __init__(self) -> None:
+ self.keys: list[str] = []
+
+ def check(self, key: str):
+ self.keys.append(key)
+ return True, 0.0
+
+ engine = MagicMock()
+ engine.engine_id = "mock"
+ config = JarvisConfig()
+ config.intelligence.default_model = "test-model"
+ config.agent.tools = "dangerous_chat"
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "code:execute")
+ policy.deny("tool_chat_agent", "code:execute")
+ limiter = _RecordingLimiter()
+
+ AgentRegistry.register_value("tool_chat_agent", _ToolChatAgent)
+ ToolRegistry.register_value("dangerous_chat", _DangerousChatTool)
+
+ with (
+ patch("openjarvis.cli.chat_cmd.load_config", return_value=config),
+ patch("openjarvis.engine.get_engine", return_value=("mock", engine)),
+ patch("openjarvis.intelligence.register_builtin_models"),
+ patch(
+ "openjarvis.security.setup_security",
+ return_value=SecurityContext(
+ engine=engine,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ ),
+ ),
+ patch(
+ "openjarvis.cli._model_switch.tty_wants_model_picker",
+ return_value=False,
+ ),
+ patch(
+ "openjarvis.cli._runtime_panel.tty_wants_runtime_panel",
+ return_value=False,
+ ),
+ ):
+ result = CliRunner().invoke(
+ chat,
+ ["--agent", "tool_chat_agent", "--model", "test-model"],
+ input="run tool\n/quit\n",
+ )
+
+ assert result.exit_code == 0
+ assert "code:execute" in result.output
+ assert "chat executed!" not in result.output
+ assert "Confirm:" not in result.output
+ assert limiter.keys == ["tool_chat_agent:dangerous_chat"]
diff --git a/tests/cli/test_cli_picker_integration.py b/tests/cli/test_cli_picker_integration.py
index 481cd8de..9cb46179 100644
--- a/tests/cli/test_cli_picker_integration.py
+++ b/tests/cli/test_cli_picker_integration.py
@@ -186,7 +186,12 @@ class TestChatPickerIntegration:
assert result.exit_code == 0
wants_panel.assert_not_called()
engine.generate.assert_called_once()
- assert engine.generate.call_args.kwargs == {"model": "gpt-4o-mini"}
+ kwargs = engine.generate.call_args.kwargs
+ assert kwargs["model"] == "gpt-4o-mini"
+ # Security engine wrappers may make their generic inference defaults
+ # explicit; cloud calls must still never inherit Ollama-only knobs.
+ assert "num_ctx" not in kwargs
+ assert "num_gpu" not in kwargs
def test_cloud_chat_rejects_ollama_runtime_flags(self) -> None:
engine = MagicMock()
diff --git a/tests/cli/test_serve_single_build.py b/tests/cli/test_serve_single_build.py
index aadf3af9..087108e6 100644
--- a/tests/cli/test_serve_single_build.py
+++ b/tests/cli/test_serve_single_build.py
@@ -94,7 +94,15 @@ def _repopulate_registries() -> None:
pass
-def _run_serve(tmp_path, monkeypatch, *, build_spy, set_system_spy):
+def _run_serve(
+ tmp_path,
+ monkeypatch,
+ *,
+ build_spy,
+ set_system_spy,
+ security_primitives=None,
+ channel_backend=None,
+):
"""Invoke ``jarvis serve`` with all heavy/blocking pieces stubbed out.
Returns the CliRunner result. The server is never actually started
@@ -118,7 +126,9 @@ def _run_serve(tmp_path, monkeypatch, *, build_spy, set_system_spy):
config.agent.context_from_memory = False
config.telemetry.enabled = False
config.traces.enabled = False
- config.channel.enabled = False
+ config.channel.enabled = channel_backend is not None
+ if channel_backend is not None:
+ config.channel.default_channel = "test-channel"
config.skills.enabled = False
config.server.host = "127.0.0.1"
config.server.port = 8123
@@ -141,13 +151,19 @@ def _run_serve(tmp_path, monkeypatch, *, build_spy, set_system_spy):
monkeypatch.setattr(serve_mod, "get_engine", lambda *a, **k: ("mock", engine))
monkeypatch.setattr(serve_mod, "discover_engines", lambda *a, **k: {})
monkeypatch.setattr(serve_mod, "discover_models", lambda *a, **k: {})
+ if channel_backend is not None:
+ monkeypatch.setattr(
+ "openjarvis.system.builder.SystemBuilder._resolve_channel",
+ lambda *args, **kwargs: channel_backend,
+ )
# setup_security returns its own context; pass the engine straight through
# so we don't need real guardrails wired up.
sec = MagicMock()
sec.engine = engine
- sec.capability_policy = None
- sec.audit_logger = None
+ if security_primitives is None:
+ security_primitives = (None, None, None)
+ sec.capability_policy, sec.rate_limiter, sec.audit_logger = security_primitives
monkeypatch.setattr("openjarvis.security.setup_security", lambda *a, **k: sec)
with (
@@ -202,11 +218,15 @@ def test_executor_receives_required_system_attrs(tmp_path, monkeypatch):
# Preserve real behaviour so the executor is usable afterwards.
self._system = system
+ policy = object()
+ limiter = object()
+ audit = object()
result = _run_serve(
tmp_path,
monkeypatch,
build_spy=build_spy,
set_system_spy=_capture_set_system,
+ security_primitives=(policy, limiter, audit),
)
assert result.exit_code == 0, result.output
@@ -225,3 +245,40 @@ def test_executor_receives_required_system_attrs(tmp_path, monkeypatch):
assert system.engine is not None
assert system.model == "test-model"
assert system.config is not None
+ assert system.capability_policy is policy
+ assert system.rate_limiter is limiter
+ assert system.audit_logger is audit
+ assert system.tool_executor._capability_policy is policy
+ assert system.tool_executor._rate_limiter is limiter
+ assert system.tool_executor._agent_id == system.config.server.agent
+
+
+def test_channel_system_receives_remote_security_primitives(tmp_path, monkeypatch):
+ from openjarvis.system import JarvisSystem
+
+ captured = {}
+
+ def _capture_wire(self, channel):
+ captured["system"] = self
+
+ monkeypatch.setattr(JarvisSystem, "wire_channel", _capture_wire)
+ policy = object()
+ limiter = object()
+ audit = object()
+ channel = MagicMock(channel_id="test-channel")
+
+ result = _run_serve(
+ tmp_path,
+ monkeypatch,
+ build_spy=MagicMock(),
+ set_system_spy=MagicMock(),
+ security_primitives=(policy, limiter, audit),
+ channel_backend=channel,
+ )
+
+ assert result.exit_code == 0, result.output
+ system = captured.get("system")
+ assert system is not None
+ assert system.capability_policy is policy
+ assert system.rate_limiter is limiter
+ assert system.audit_logger is audit
diff --git a/tests/cli/test_standalone_security.py b/tests/cli/test_standalone_security.py
new file mode 100644
index 00000000..62f82f01
--- /dev/null
+++ b/tests/cli/test_standalone_security.py
@@ -0,0 +1,167 @@
+"""Standalone channel/research launchers inherit configured security."""
+
+from __future__ import annotations
+
+import sys
+import types
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+from click.testing import CliRunner
+
+from openjarvis.core.config import JarvisConfig
+from openjarvis.security import SecurityContext
+
+
+def _security(raw_engine, wrapped_engine, policy, limiter):
+ return MagicMock(
+ return_value=SecurityContext(
+ engine=wrapped_engine,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ )
+ )
+
+
+def test_deep_research_setup_chat_wires_security(monkeypatch):
+ from openjarvis.cli.deep_research_setup_cmd import _launch_chat
+
+ raw_engine = MagicMock(name="raw-engine")
+ wrapped_engine = MagicMock(name="wrapped-engine")
+ wrapped_engine.health.return_value = True
+ wrapped_engine.list_models.return_value = ["qwen3.5:4b"]
+ policy = object()
+ limiter = object()
+ setup = _security(raw_engine, wrapped_engine, policy, limiter)
+ captured = {}
+
+ class _Agent:
+ def __init__(self, **kwargs):
+ captured.update(kwargs)
+
+ def run(self, text):
+ return SimpleNamespace(content="done")
+
+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda: JarvisConfig())
+ monkeypatch.setattr("openjarvis.engine.ollama.OllamaEngine", lambda: raw_engine)
+ monkeypatch.setattr("openjarvis.security.setup_security", setup)
+ monkeypatch.setattr("openjarvis.agents.deep_research.DeepResearchAgent", _Agent)
+ console = MagicMock()
+ console.input.return_value = "/quit"
+
+ _launch_chat(MagicMock(), console)
+
+ assert captured["engine"] is wrapped_engine
+ assert captured["capability_policy"] is policy
+ assert captured["rate_limiter"] is limiter
+ assert captured["agent_id"] == "cli:deep-research"
+ assert captured["bus"] is setup.call_args.args[2]
+
+
+def test_imessage_foreground_wires_security(monkeypatch):
+ from openjarvis.cli.channels_cmd import imessage_start
+
+ raw_engine = MagicMock(name="raw-engine")
+ wrapped_engine = MagicMock(name="wrapped-engine")
+ policy = object()
+ limiter = object()
+ setup = _security(raw_engine, wrapped_engine, policy, limiter)
+ captured = {}
+ run_daemon = MagicMock()
+
+ class _Agent:
+ def __init__(self, **kwargs):
+ captured.update(kwargs)
+
+ def run(self, text):
+ return SimpleNamespace(content="done")
+
+ monkeypatch.setattr("openjarvis.channels.imessage_daemon.is_running", lambda: False)
+ monkeypatch.setattr("openjarvis.channels.imessage_daemon.run_daemon", run_daemon)
+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda: JarvisConfig())
+ monkeypatch.setattr("openjarvis.engine.ollama.OllamaEngine", lambda: raw_engine)
+ monkeypatch.setattr("openjarvis.security.setup_security", setup)
+ monkeypatch.setattr("openjarvis.agents.deep_research.DeepResearchAgent", _Agent)
+
+ result = CliRunner().invoke(
+ imessage_start,
+ ["[email protected]", "--foreground"],
+ )
+
+ assert result.exit_code == 0
+ assert captured["engine"] is wrapped_engine
+ assert captured["capability_policy"] is policy
+ assert captured["rate_limiter"] is limiter
+ assert captured["agent_id"] == "channel:imessage"
+ assert captured["bus"] is setup.call_args.args[2]
+ run_daemon.assert_called_once()
+
+
+def test_slack_daemon_wires_security(monkeypatch, tmp_path):
+ from openjarvis.channels import slack_daemon
+
+ handlers = {}
+
+ class _App:
+ def __init__(self, **kwargs):
+ pass
+
+ def event(self, name):
+ def _decorate(function):
+ handlers[name] = function
+ return function
+
+ return _decorate
+
+ class _Handler:
+ def __init__(self, app, token):
+ pass
+
+ def start(self):
+ return None
+
+ def close(self):
+ return None
+
+ bolt = types.ModuleType("slack_bolt")
+ bolt.App = _App
+ adapter = types.ModuleType("slack_bolt.adapter")
+ socket_mode = types.ModuleType("slack_bolt.adapter.socket_mode")
+ socket_mode.SocketModeHandler = _Handler
+ monkeypatch.setitem(sys.modules, "slack_bolt", bolt)
+ monkeypatch.setitem(sys.modules, "slack_bolt.adapter", adapter)
+ monkeypatch.setitem(sys.modules, "slack_bolt.adapter.socket_mode", socket_mode)
+
+ raw_engine = MagicMock(name="raw-engine")
+ wrapped_engine = MagicMock(name="wrapped-engine")
+ policy = object()
+ limiter = object()
+ setup = _security(raw_engine, wrapped_engine, policy, limiter)
+ captured = {}
+
+ class _Agent:
+ def __init__(self, **kwargs):
+ captured.update(kwargs)
+
+ def run(self, text):
+ return SimpleNamespace(content="done")
+
+ monkeypatch.setattr(slack_daemon, "_PID_FILE", str(tmp_path / "slack.pid"))
+ monkeypatch.setattr(slack_daemon.signal, "signal", MagicMock())
+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda: JarvisConfig())
+ monkeypatch.setattr("openjarvis.engine.ollama.OllamaEngine", lambda: raw_engine)
+ monkeypatch.setattr("openjarvis.security.setup_security", setup)
+ monkeypatch.setattr("openjarvis.agents.deep_research.DeepResearchAgent", _Agent)
+ monkeypatch.setattr(
+ "openjarvis.server.agent_manager_routes._build_deep_research_tools",
+ lambda **kwargs: [],
+ )
+
+ slack_daemon.run_slack_daemon("bot", "app", "test-model")
+
+ assert captured["engine"] is wrapped_engine
+ assert captured["capability_policy"] is policy
+ assert captured["rate_limiter"] is limiter
+ assert captured["agent_id"] == "channel:slack"
+ assert captured["bus"] is setup.call_args.args[2]
+ assert "message" in handlers
diff --git a/tests/mcp/test_discovery.py b/tests/mcp/test_discovery.py
index ef3e5c78..76740952 100644
--- a/tests/mcp/test_discovery.py
+++ b/tests/mcp/test_discovery.py
@@ -215,6 +215,38 @@ def test_builder_retains_full_mcp_pool_for_managed_agents() -> None:
assert builder._mcp_tools == [external]
+def test_builder_wires_security_context_into_internal_mcp_server() -> None:
+ """The builder's MCP construction site must not drop dispatch gates."""
+
+ from openjarvis.core.config import JarvisConfig
+ from openjarvis.system import SystemBuilder
+
+ config = JarvisConfig()
+ policy = object()
+ limiter = object()
+ bus = object()
+ builder = SystemBuilder(config)
+
+ with patch("openjarvis.mcp.server.MCPServer") as mcp_server_cls:
+ mcp_server_cls.return_value.get_tools.return_value = []
+ builder._resolve_tools(
+ config,
+ engine=MagicMock(),
+ model="test-model",
+ memory_backend=None,
+ bus=bus,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ )
+
+ mcp_server_cls.assert_called_once_with(
+ bus=bus,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ agent_id="system:mcp",
+ )
+
+
def test_builder_global_mcp_disable_prevents_discovery() -> None:
"""A global MCP disable is honored by every managed-agent entry path."""
diff --git a/tests/mcp/test_server.py b/tests/mcp/test_server.py
index fab260d0..048bc14d 100644
--- a/tests/mcp/test_server.py
+++ b/tests/mcp/test_server.py
@@ -4,16 +4,59 @@ from __future__ import annotations
import pytest
+from openjarvis.core.events import EventBus, EventType
+from openjarvis.core.types import ToolResult
from openjarvis.mcp.protocol import (
INVALID_PARAMS,
METHOD_NOT_FOUND,
MCPRequest,
)
from openjarvis.mcp.server import MCPServer
+from openjarvis.tools._stubs import BaseTool, ToolSpec
from openjarvis.tools.calculator import CalculatorTool
from openjarvis.tools.think import ThinkTool
+class _ProbeTool(BaseTool):
+ tool_id = "probe"
+
+ def __init__(self, name: str, capabilities: list[str]) -> None:
+ self._name = name
+ self._capabilities = capabilities
+ self.executed = False
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name=self._name,
+ description="security enforcement probe",
+ required_capabilities=self._capabilities,
+ )
+
+ def execute(self, **params) -> ToolResult:
+ self.executed = True
+ return ToolResult(tool_name=self._name, content="executed", success=True)
+
+
+class _DenyPolicy:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, str, str]] = []
+
+ def check(self, agent_id: str, capability: str, resource: str) -> bool:
+ self.calls.append((agent_id, capability, resource))
+ return False
+
+
+class _RecordingLimiter:
+ def __init__(self, allowed: bool = True) -> None:
+ self.allowed = allowed
+ self.keys: list[str] = []
+
+ def check(self, key: str) -> tuple[bool, float]:
+ self.keys.append(key)
+ return self.allowed, 1.0 if not self.allowed else 0.0
+
+
@pytest.fixture
def server():
"""Create an MCP server with calculator and think tools."""
@@ -21,6 +64,74 @@ def server():
class TestMCPServer:
+ def test_admin_capability_is_fail_closed_and_auditable(self):
+ tool = _ProbeTool("admin_probe", ["system:admin"])
+ policy = _DenyPolicy()
+ limiter = _RecordingLimiter()
+ bus = EventBus(record_history=True)
+ server = MCPServer(
+ [tool],
+ bus=bus,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ )
+
+ resp = server.handle(
+ MCPRequest(
+ method="tools/call",
+ params={"name": "admin_probe", "arguments": {}},
+ id=100,
+ )
+ )
+
+ assert resp.result["isError"] is True
+ assert "system:admin" in resp.result["content"][0]["text"]
+ assert tool.executed is False
+ assert limiter.keys == ["mcp:admin_probe"]
+ assert policy.calls == [("mcp", "system:admin", "admin_probe")]
+ denied = [
+ event
+ for event in bus.history
+ if event.event_type == EventType.CAPABILITY_DENIED
+ ]
+ assert len(denied) == 1
+ assert denied[0].data["agent_id"] == "mcp"
+
+ def test_canonical_capability_cannot_be_removed_from_mcp_tool_spec(self):
+ tool = _ProbeTool("channel_send", [])
+ policy = _DenyPolicy()
+ server = MCPServer([tool], capability_policy=policy)
+
+ resp = server.handle(
+ MCPRequest(
+ method="tools/call",
+ params={"name": "channel_send", "arguments": {}},
+ id=101,
+ )
+ )
+
+ assert resp.result["isError"] is True
+ assert tool.executed is False
+ assert policy.calls == [("mcp", "channel:send", "channel_send")]
+
+ def test_rate_limit_is_fail_closed_before_mcp_dispatch(self):
+ tool = _ProbeTool("admin_probe", ["system:admin"])
+ limiter = _RecordingLimiter(allowed=False)
+ server = MCPServer([tool], rate_limiter=limiter)
+
+ resp = server.handle(
+ MCPRequest(
+ method="tools/call",
+ params={"name": "admin_probe", "arguments": {}},
+ id=102,
+ )
+ )
+
+ assert resp.result["isError"] is True
+ assert "Rate limit exceeded" in resp.result["content"][0]["text"]
+ assert limiter.keys == ["mcp:admin_probe"]
+ assert tool.executed is False
+
def test_initialize(self, server):
req = MCPRequest(method="initialize", id=1)
resp = server.handle(req)
diff --git a/tests/sdk/test_sdk.py b/tests/sdk/test_sdk.py
index b64e19e7..6e312d7f 100644
--- a/tests/sdk/test_sdk.py
+++ b/tests/sdk/test_sdk.py
@@ -95,6 +95,76 @@ class TestJarvisAsk:
assert result == "Agent response"
j.close()
+ def test_simple_agent_ignores_tool_security_kwargs(self):
+ from openjarvis.agents.simple import SimpleAgent
+ from openjarvis.core.registry import AgentRegistry
+ from openjarvis.security import SecurityContext
+
+ engine = _make_engine("simple secured response")
+ AgentRegistry.register_value("simple", SimpleAgent)
+ with (
+ patch("openjarvis.sdk.get_engine", return_value=("mock", engine)),
+ patch(
+ "openjarvis.security.setup_security",
+ return_value=SecurityContext(
+ engine=engine,
+ capability_policy=object(),
+ rate_limiter=object(),
+ ),
+ ),
+ ):
+ j = Jarvis(config=JarvisConfig(), model="test-model")
+ result = j.ask("Hello", agent="simple")
+ j.close()
+
+ assert result == "simple secured response"
+
+ def test_direct_operation_agent_receives_policy_rate_and_identity(self):
+ from openjarvis.agents._stubs import AgentContext, AgentResult, BaseAgent
+ from openjarvis.core.registry import AgentRegistry
+ from openjarvis.security import SecurityContext
+ from openjarvis.security.capabilities import CapabilityPolicy
+
+ class _RecordingLimiter:
+ def __init__(self):
+ self.keys = []
+
+ def check(self, key):
+ self.keys.append(key)
+ return True, 0.0
+
+ class _DirectSDKAgent(BaseAgent):
+ agent_id = "direct-sdk"
+ required_capabilities = ("code:execute",)
+
+ def run(self, input, context: AgentContext | None = None, **kwargs):
+ return self._execution_denied_result() or AgentResult(content="ran")
+
+ engine = _make_engine()
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "code:execute")
+ policy.deny("direct-sdk", "code:execute")
+ limiter = _RecordingLimiter()
+ AgentRegistry.register_value("direct-sdk", _DirectSDKAgent)
+
+ with (
+ patch("openjarvis.sdk.get_engine", return_value=("mock", engine)),
+ patch(
+ "openjarvis.security.setup_security",
+ return_value=SecurityContext(
+ engine=engine,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ ),
+ ),
+ ):
+ j = Jarvis(config=JarvisConfig(), model="test-model")
+ result = j.ask("run", agent="direct-sdk")
+ j.close()
+
+ assert "code:execute" in result
+ assert limiter.keys == ["direct-sdk:agent_run"]
+
def test_ask_with_agent_wires_persona(self, tmp_path):
from openjarvis.agents.simple import SimpleAgent
from openjarvis.core.registry import AgentRegistry
diff --git a/tests/sdk/test_system.py b/tests/sdk/test_system.py
index 79f0c138..d8d8cbe8 100644
--- a/tests/sdk/test_system.py
+++ b/tests/sdk/test_system.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from dataclasses import fields
from unittest.mock import MagicMock, patch
import pytest
@@ -40,6 +41,58 @@ class TestJarvisSystem:
assert system.memory_backend is memory_backend
assert system.mcp_tools == []
+ def test_rate_limiter_is_after_all_preexisting_positional_fields(self):
+ field_names = [field.name for field in fields(JarvisSystem)]
+ assert field_names[-2:] == ["mcp_tools", "rate_limiter"]
+
+ legacy_values = [object() for _ in field_names[:-1]]
+ system = JarvisSystem(*legacy_values)
+
+ assert system.mcp_tools is legacy_values[-1]
+ assert system.rate_limiter is None
+
+ def test_system_orchestrator_wires_direct_agent_security(self):
+ from openjarvis.agents._stubs import AgentContext, AgentResult, BaseAgent
+ from openjarvis.core.registry import AgentRegistry
+ from openjarvis.security.capabilities import CapabilityPolicy
+
+ class _Limiter:
+ def __init__(self):
+ self.keys = []
+
+ def check(self, key):
+ self.keys.append(key)
+ return True, 0.0
+
+ class _DirectAgent(BaseAgent):
+ agent_id = "system-direct"
+ required_capabilities = ("code:execute",)
+
+ def run(self, input, context: AgentContext | None = None, **kwargs):
+ return self._execution_denied_result() or AgentResult(content="ran")
+
+ AgentRegistry.register_value("system-direct", _DirectAgent)
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "code:execute")
+ policy.deny("system-direct", "code:execute")
+ limiter = _Limiter()
+ config = JarvisConfig()
+ config.agent.context_from_memory = False
+ system = JarvisSystem(
+ config=config,
+ bus=EventBus(record_history=True),
+ engine=MagicMock(),
+ engine_key="mock",
+ model="test-model",
+ capability_policy=policy,
+ rate_limiter=limiter,
+ )
+
+ result = system.ask("run", agent="system-direct")
+
+ assert "code:execute" in result["content"]
+ assert limiter.keys == ["system-direct:agent_run"]
+
def test_ask_direct_mode(self):
engine = MagicMock()
engine.generate.return_value = {
diff --git a/tests/security/test_audit.py b/tests/security/test_audit.py
index 6e86e8d5..cb5754db 100644
--- a/tests/security/test_audit.py
+++ b/tests/security/test_audit.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import time
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from openjarvis.core.events import EventBus, EventType
@@ -167,3 +168,51 @@ class TestAuditLogger:
logger2 = AuditLogger(db_path=db_path)
assert logger2.count() == 1
logger2.close()
+
+ def test_concurrent_writers_preserve_single_hash_chain(
+ self, tmp_path: Path
+ ) -> None:
+ logger = AuditLogger(db_path=tmp_path / "audit.db")
+
+ def _write(index: int) -> None:
+ logger.log(
+ SecurityEvent(
+ event_type=SecurityEventType.TOOL_EXECUTED,
+ timestamp=float(index),
+ content_preview=f"tool-{index}",
+ action_taken="success",
+ )
+ )
+
+ with ThreadPoolExecutor(max_workers=12) as pool:
+ list(pool.map(_write, range(100)))
+
+ assert logger.count() == 100
+ assert logger.verify_chain() == (True, None)
+ logger.close()
+
+ def test_multiple_logger_instances_share_one_atomic_hash_chain(
+ self, tmp_path: Path
+ ) -> None:
+ db_path = tmp_path / "audit.db"
+ loggers = [AuditLogger(db_path=db_path) for _ in range(4)]
+
+ def _write(index: int) -> None:
+ loggers[index % len(loggers)].log(
+ SecurityEvent(
+ event_type=SecurityEventType.TOOL_EXECUTED,
+ timestamp=float(index),
+ content_preview=f"multi-{index}",
+ action_taken="success",
+ )
+ )
+
+ try:
+ with ThreadPoolExecutor(max_workers=16) as pool:
+ list(pool.map(_write, range(400)))
+
+ assert loggers[0].count() == 400
+ assert loggers[0].verify_chain() == (True, None)
+ finally:
+ for logger in loggers:
+ logger.close()
diff --git a/tests/security/test_builder_skill_identity.py b/tests/security/test_builder_skill_identity.py
new file mode 100644
index 00000000..94ee3fd8
--- /dev/null
+++ b/tests/security/test_builder_skill_identity.py
@@ -0,0 +1,114 @@
+"""Ensure nested skill execution preserves the caller security identity."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from openjarvis.core.config import JarvisConfig
+from openjarvis.core.types import ToolCall
+from openjarvis.security.capabilities import CapabilityPolicy
+from openjarvis.skills.executor import SkillExecutor
+from openjarvis.skills.tool_adapter import SkillTool
+from openjarvis.skills.types import SkillManifest, SkillStep
+from openjarvis.system import SystemBuilder
+from openjarvis.tools.repl import ReplTool
+
+
+class _HealthyEngine:
+ def health(self) -> bool:
+ return True
+
+
+class _PipelineSkillManager:
+ inner_executor = None
+
+ def __init__(self, *args, **kwargs) -> None:
+ self._executor = None
+
+ def discover(self, paths=None) -> None:
+ pass
+
+ def set_tool_executor(self, executor) -> None:
+ self._executor = executor
+
+ def get_skill_tools(self, *, tool_executor=None):
+ executor = tool_executor or self._executor
+ type(self).inner_executor = executor
+ manifest = SkillManifest(
+ name="restricted_pipeline",
+ steps=[
+ SkillStep(
+ tool_name="repl",
+ arguments_template='{"code": "sentinel = 42"}',
+ )
+ ],
+ )
+ return [SkillTool(manifest, SkillExecutor(executor))]
+
+ def get_few_shot_examples(self):
+ return []
+
+
+def test_builder_nested_skill_cannot_fall_back_to_default_identity(
+ tmp_path, monkeypatch
+) -> None:
+ config = JarvisConfig()
+ config.telemetry.enabled = False
+ config.traces.enabled = False
+ config.skills.enabled = True
+ config.skills.skills_dir = str(tmp_path / "skills")
+ config.agent_manager.enabled = False
+ config.sessions.enabled = False
+ config.scheduler.enabled = False
+ config.workflow.enabled = False
+
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "code:execute")
+ policy.deny("restricted", "code:execute")
+ repl = ReplTool()
+
+ monkeypatch.setattr(
+ "openjarvis.security.setup_security",
+ lambda config, engine, bus: SimpleNamespace(
+ engine=engine,
+ capability_policy=policy,
+ rate_limiter=None,
+ audit_logger=None,
+ ),
+ )
+ monkeypatch.setattr("openjarvis.skills.manager.SkillManager", _PipelineSkillManager)
+
+ builder = (
+ SystemBuilder(config)
+ .engine_instance(_HealthyEngine())
+ .model("model")
+ .agent("restricted")
+ .telemetry(False)
+ .traces(False)
+ .speech(False)
+ )
+ monkeypatch.setattr(builder, "_resolve_memory", lambda config: None)
+ monkeypatch.setattr(builder, "_resolve_channel", lambda config, bus: None)
+ monkeypatch.setattr(builder, "_resolve_tools", lambda *args, **kwargs: [repl])
+ monkeypatch.setattr(builder, "_setup_sandbox", lambda config: None)
+ monkeypatch.setattr(builder, "_setup_scheduler", lambda config, bus: (None, None))
+ monkeypatch.setattr(builder, "_setup_workflow", lambda config, bus: None)
+ monkeypatch.setattr(builder, "_setup_sessions", lambda config: None)
+ monkeypatch.setattr(builder, "_setup_learning_orchestrator", lambda config: None)
+
+ system = builder.build()
+ inner = _PipelineSkillManager.inner_executor
+ assert inner._agent_id == "restricted"
+ assert system.tool_executor._agent_id == "restricted"
+
+ result = system.tool_executor.execute(
+ ToolCall(
+ id="nested-skill-denied",
+ name="skill_restricted_pipeline",
+ arguments="{}",
+ )
+ )
+
+ assert not result.success
+ assert "code:execute" in result.content
+ assert repl._sessions == {}
diff --git a/tests/security/test_capabilities.py b/tests/security/test_capabilities.py
index 958f2328..78c6be8c 100644
--- a/tests/security/test_capabilities.py
+++ b/tests/security/test_capabilities.py
@@ -2,11 +2,20 @@
from __future__ import annotations
+import ast
+import json
+from pathlib import Path
+
+import pytest
+
+from openjarvis.core.types import ToolCall, ToolResult
from openjarvis.security.capabilities import (
DEFAULT_TOOL_CAPABILITIES,
Capability,
CapabilityPolicy,
+ canonical_tool_capabilities,
)
+from openjarvis.tools._stubs import BaseTool, ToolExecutor, ToolSpec
class TestCapability:
@@ -61,6 +70,25 @@ class TestCapabilityPolicy:
policy.deny("agent1", "code:execute")
assert not policy.check("agent1", "code:execute")
+ def test_agent_deny_overrides_default_agent_grant(self):
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "code:execute")
+ policy.deny("agent1", "code:execute")
+
+ assert not policy.check("agent1", "code:execute")
+
+ def test_unconfigured_agent_inherits_default_agent_grant(self):
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "file:read")
+
+ assert policy.check("unconfigured-agent", "file:read")
+ assert not policy.check("unconfigured-agent", "file:write")
+
+ def test_anonymous_executor_cannot_inherit_default_grants(self):
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "code:execute")
+ assert not policy.check("", "code:execute")
+
def test_resource_pattern(self):
policy = CapabilityPolicy(default_deny=True)
policy.grant("agent1", "file:read", pattern="/safe/*")
@@ -103,12 +131,151 @@ class TestCapabilityPolicy:
assert loaded.check("agent1", "file:read")
assert not loaded.check("agent1", "code:execute")
+ def test_empty_explicit_policy_does_not_inherit_default_grants(self, tmp_path):
+ path = tmp_path / "policy.json"
+ path.write_text(
+ json.dumps(
+ {
+ "agents": [
+ {
+ "agent_id": "_default",
+ "grants": [{"capability": "code:execute"}],
+ },
+ {"agent_id": "restricted", "grants": []},
+ ]
+ }
+ )
+ )
+ policy = CapabilityPolicy(policy_path=str(path), default_deny=True)
+ assert policy.check("unconfigured", "code:execute")
+ assert not policy.check("restricted", "code:execute")
+
def test_load_nonexistent_file(self):
- policy = CapabilityPolicy(policy_path="/nonexistent/path.json")
- # Should not raise, just have no policies
- assert policy.check("agent1", "file:read")
+ with pytest.raises(FileNotFoundError):
+ CapabilityPolicy(policy_path="/nonexistent/path.json")
+
+ @pytest.mark.parametrize(
+ "contents",
+ [
+ "{not json}",
+ "[]",
+ "{}",
+ '{"agents": {}}',
+ '{"agents": [{}]}',
+ '{"agents": [{"agent_id": "a", "deny": "code:execute"}]}',
+ '{"agents": [{"agent_id": "a", "grants": [{"pattern": "*"}]}]}',
+ ],
+ )
+ def test_load_invalid_policy_does_not_silently_allow_tools(
+ self, tmp_path, contents
+ ):
+ path = tmp_path / "invalid-policy.json"
+ path.write_text(contents)
+ with pytest.raises(ValueError):
+ CapabilityPolicy(policy_path=str(path))
def test_default_tool_capabilities(self):
assert "file:read" in DEFAULT_TOOL_CAPABILITIES.get("file_read", [])
assert "network:fetch" in DEFAULT_TOOL_CAPABILITIES.get("web_search", [])
assert "code:execute" in DEFAULT_TOOL_CAPABILITIES.get("code_interpreter", [])
+
+ def test_every_registered_builtin_has_an_explicit_inventory_entry(self):
+ root = Path(__file__).parents[2] / "src" / "openjarvis"
+ registered: set[str] = set()
+ for path in [
+ *(root / "tools").rglob("*.py"),
+ root / "scheduler" / "tools.py",
+ ]:
+ tree = ast.parse(path.read_text(), filename=str(path))
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.ClassDef, ast.FunctionDef)):
+ continue
+ for decorator in node.decorator_list:
+ if not isinstance(decorator, ast.Call) or not decorator.args:
+ continue
+ func = decorator.func
+ if (
+ isinstance(func, ast.Attribute)
+ and func.attr == "register"
+ and isinstance(func.value, ast.Name)
+ and func.value.id == "ToolRegistry"
+ and isinstance(decorator.args[0], ast.Constant)
+ and isinstance(decorator.args[0].value, str)
+ ):
+ registered.add(decorator.args[0].value)
+
+ assert registered == set(DEFAULT_TOOL_CAPABILITIES)
+
+ def test_real_repl_cannot_execute_under_default_deny(self):
+ from openjarvis.tools.repl import ReplTool
+
+ tool = ReplTool()
+ executor = ToolExecutor(
+ [tool],
+ capability_policy=CapabilityPolicy(default_deny=True),
+ agent_id="restricted",
+ )
+
+ result = executor.execute(
+ ToolCall(
+ id="repl-denied",
+ name="repl",
+ arguments=json.dumps({"code": "sentinel = 42"}),
+ )
+ )
+
+ assert not result.success
+ assert "code:execute" in result.content
+ assert tool._sessions == {}
+
+ def test_uninventoried_future_builtin_fails_closed(self):
+ class FutureBuiltin(BaseTool):
+ @property
+ def spec(self):
+ return ToolSpec(name="future_builtin", description="future")
+
+ def execute(self, **params):
+ return ToolResult(tool_name="future_builtin", content="ran")
+
+ FutureBuiltin.__module__ = "openjarvis.tools.future"
+ tool = FutureBuiltin()
+ assert canonical_tool_capabilities(tool) == [Capability.SYSTEM_ADMIN]
+
+ result = ToolExecutor(
+ [tool],
+ capability_policy=CapabilityPolicy(default_deny=True),
+ agent_id="restricted",
+ ).execute(ToolCall(id="future-denied", name="future_builtin", arguments="{}"))
+ assert not result.success
+ assert "system:admin" in result.content
+
+ def test_mcp_adapter_cannot_spoof_reviewed_safe_builtin_name(self):
+ from unittest.mock import MagicMock
+
+ from openjarvis.tools.mcp_adapter import MCPToolAdapter
+
+ client = MagicMock()
+ client.call_tool.return_value = {
+ "content": [{"type": "text", "text": "remote executed"}]
+ }
+ tool = MCPToolAdapter(
+ client,
+ ToolSpec(name="calculator", description="remote safe-name spoof"),
+ )
+
+ result = ToolExecutor(
+ [tool],
+ capability_policy=CapabilityPolicy(default_deny=True),
+ agent_id="restricted",
+ ).execute(ToolCall(id="mcp-spoof", name="calculator", arguments="{}"))
+
+ assert not result.success
+ assert "tool:invoke" in result.content
+ client.call_tool.assert_not_called()
+
+ def test_reviewed_safe_floor_is_pinned_to_real_builtin_classes(self):
+ from openjarvis.tools.calculator import CalculatorTool
+ from openjarvis.tools.think import ThinkTool
+
+ assert canonical_tool_capabilities(CalculatorTool()) == []
+ assert canonical_tool_capabilities(ThinkTool()) == []
diff --git a/tests/security/test_security_wiring.py b/tests/security/test_security_wiring.py
index eca55808..5e80d277 100644
--- a/tests/security/test_security_wiring.py
+++ b/tests/security/test_security_wiring.py
@@ -11,7 +11,12 @@ from openjarvis.core.config import (
SecurityConfig,
)
from openjarvis.core.events import EventBus
+from openjarvis.core.registry import AgentRegistry
+from openjarvis.core.types import ToolCall
from openjarvis.security import setup_security
+from openjarvis.security.capabilities import CapabilityPolicy
+from openjarvis.system import JarvisSystem
+from openjarvis.tools.repl import ReplTool
class _ConcreteAgent(ToolUsingAgent):
@@ -23,6 +28,29 @@ class _ConcreteAgent(ToolUsingAgent):
return AgentResult(content="ok")
+class _CallingAgent(ToolUsingAgent):
+ agent_id = "class-default-identity"
+
+ def run(self, input, context=None, **kwargs):
+ result = self._executor.execute(
+ ToolCall(
+ id="agent-repl-denied",
+ name="repl",
+ arguments='{"code": "sentinel = 42"}',
+ )
+ )
+ return AgentResult(content=result.content, tool_results=[result])
+
+
+class _RecordingLimiter:
+ def __init__(self) -> None:
+ self.keys = []
+
+ def check(self, key):
+ self.keys.append(key)
+ return True, 0.0
+
+
def _make_mock_engine() -> MagicMock:
engine = MagicMock()
engine.engine_id = "mock"
@@ -80,3 +108,72 @@ class TestCapabilityPolicyReachesExecutor:
assert agent._executor._capability_policy is None
# Engine should be the original, unwrapped
assert sec.engine is engine
+
+ def test_orchestrator_propagates_runtime_identity_and_limiter(self) -> None:
+ key = "restricted-orchestrator-agent"
+ AgentRegistry.register_value(key, _CallingAgent)
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "code:execute")
+ policy.deny(key, "code:execute")
+ limiter = _RecordingLimiter()
+ repl = ReplTool()
+ config = JarvisConfig()
+ config.agent.context_from_memory = False
+ config.traces.enabled = False
+ system = JarvisSystem(
+ config=config,
+ bus=EventBus(),
+ engine=_make_mock_engine(),
+ engine_key="mock",
+ model="m",
+ agent_name=key,
+ tools=[repl],
+ capability_policy=policy,
+ rate_limiter=limiter,
+ )
+
+ result = system.ask("run")
+
+ assert "code:execute" in result["content"]
+ assert "denied" in result["content"]
+ assert limiter.keys == [f"{key}:repl"]
+ assert repl._sessions == {}
+
+ def test_cli_ask_propagates_runtime_identity_and_limiter(self, monkeypatch) -> None:
+ import importlib
+
+ ask_module = importlib.import_module("openjarvis.cli.ask")
+
+ key = "restricted-cli-ask-agent"
+ AgentRegistry.register_value(key, _CallingAgent)
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("_default", "code:execute")
+ policy.deny(key, "code:execute")
+ limiter = _RecordingLimiter()
+ repl = ReplTool()
+ config = JarvisConfig()
+ config.agent.context_from_memory = False
+ monkeypatch.setattr(ask_module, "_build_tools", lambda *args: [repl])
+ monkeypatch.setattr(
+ "openjarvis.mcp.loader.load_mcp_tools_from_config",
+ lambda *args, **kwargs: ([], []),
+ )
+
+ result = ask_module._run_agent(
+ key,
+ "run",
+ _make_mock_engine(),
+ "m",
+ ["repl"],
+ config,
+ EventBus(),
+ 0.1,
+ 32,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ )
+
+ assert "code:execute" in result.content
+ assert "denied" in result.content
+ assert limiter.keys == [f"{key}:repl"]
+ assert repl._sessions == {}
diff --git a/tests/security/test_setup_security.py b/tests/security/test_setup_security.py
index 2ad1c181..9478c3ea 100644
--- a/tests/security/test_setup_security.py
+++ b/tests/security/test_setup_security.py
@@ -71,6 +71,42 @@ class TestSetupSecurityEnabled:
# Should not raise — scanner failure is caught
assert isinstance(sec, SecurityContext)
+ @pytest.mark.parametrize("profile", ["", "personal", "shared", "server"])
+ def test_enabled_policy_fails_closed_when_initialization_fails(
+ self, monkeypatch, profile
+ ) -> None:
+ cfg = _make_config(caps_enabled=True)
+ cfg.security.profile = profile
+
+ def _broken_policy(*args, **kwargs):
+ raise RuntimeError("policy unavailable")
+
+ monkeypatch.setattr(
+ "openjarvis.security.capabilities.CapabilityPolicy",
+ _broken_policy,
+ )
+
+ with pytest.raises(RuntimeError, match="Capability policy initialization"):
+ setup_security(cfg, _make_mock_engine(), EventBus())
+
+ @pytest.mark.parametrize("profile", ["shared", "server"])
+ def test_server_rate_limiter_fails_closed_when_initialization_fails(
+ self, monkeypatch, profile
+ ) -> None:
+ cfg = _make_config(caps_enabled=False)
+ cfg.security.profile = profile
+
+ def _broken_limiter(*args, **kwargs):
+ raise RuntimeError("limiter unavailable")
+
+ monkeypatch.setattr(
+ "openjarvis.security.rate_limiter.RateLimiter",
+ _broken_limiter,
+ )
+
+ with pytest.raises(RuntimeError, match="Rate limiter initialization"):
+ setup_security(cfg, _make_mock_engine(), EventBus())
+
class TestSetupSecurityDisabled:
def test_returns_original_engine(self) -> None:
@@ -80,3 +116,44 @@ class TestSetupSecurityDisabled:
assert sec.engine is engine
assert sec.capability_policy is None
assert sec.audit_logger is None
+
+
[email protected]("profile", ["shared", "server"])
+ ("settings", "enabled", "default_deny"),
+ [
+ ('policy_path = "policy.json"', True, True),
+ ("enabled = false", False, True),
+ ("default_deny = false", True, False),
+ ],
+)
+def test_partial_capability_config_preserves_profile_defaults(
+ tmp_path,
+ profile,
+ settings,
+ enabled,
+ default_deny,
+):
+ from openjarvis.core.config import load_config
+
+ path = tmp_path / "config.toml"
+ path.write_text(
+ f'[security]\nprofile = "{profile}"\n[security.capabilities]\n{settings}\n'
+ )
+ config = load_config(path)
+ assert config.security.capabilities.enabled is enabled
+ assert config.security.capabilities.default_deny is default_deny
+
+
+def test_empty_explicit_policy_grants_no_baseline_privileges(tmp_path):
+ policy_path = tmp_path / "deny-all.json"
+ policy_path.write_text('{"agents": []}')
+ config = _make_config(caps_enabled=True)
+ config.security.capabilities.default_deny = True
+ config.security.capabilities.policy_path = str(policy_path)
+ security = setup_security(config, _make_mock_engine(), EventBus())
+ try:
+ for capability in ("file:read", "network:fetch", "memory:read", "memory:write"):
+ assert not security.capability_policy.check("arbitrary-agent", capability)
+ finally:
+ security.audit_logger.close()
diff --git a/tests/server/test_agent_manager_routes.py b/tests/server/test_agent_manager_routes.py
index 9d3aab54..00675b7b 100644
--- a/tests/server/test_agent_manager_routes.py
+++ b/tests/server/test_agent_manager_routes.py
@@ -288,6 +288,51 @@ class TestAgentManagerRoutes:
)
assert res.status_code == 404
+ @pytest.mark.parametrize("route_kind", ["run", "immediate"])
+ def test_remote_tick_facade_carries_policy_and_limiter(
+ self, manager, client, monkeypatch, route_kind
+ ):
+ from openjarvis.agents import executor as executor_module
+
+ captured = []
+
+ class _CapturingExecutor:
+ def __init__(self, **kwargs):
+ pass
+
+ def set_system(self, system):
+ captured.append(system)
+
+ def execute_tick(self, *args, **kwargs):
+ pass
+
+ policy = object()
+ limiter = object()
+ client.app.state.capability_policy = policy
+ client.app.state.rate_limiter = limiter
+ client.app.state.engine = MagicMock()
+ client.app.state.model = "test-model"
+ client.app.state.config = None
+ monkeypatch.setattr(executor_module, "AgentExecutor", _CapturingExecutor)
+ monkeypatch.setattr(
+ "openjarvis.server.agent_manager_routes._start_managed_worker",
+ lambda state, target, **kwargs: target(),
+ )
+ agent = manager.create_agent(name=f"remote-{route_kind}", agent_type="simple")
+
+ if route_kind == "run":
+ response = client.post(f"/v1/managed-agents/{agent['id']}/run")
+ else:
+ response = client.post(
+ f"/v1/managed-agents/{agent['id']}/messages",
+ json={"content": "now", "mode": "immediate", "stream": False},
+ )
+
+ assert response.status_code == 200
+ assert len(captured) == 1
+ assert captured[0].capability_policy is policy
+ assert captured[0].rate_limiter is limiter
+
def test_run_agent_concurrent_returns_409(tmp_path):
"""Rapid Run Now clicks should not spawn multiple ticks."""
@@ -771,6 +816,30 @@ class TestLightweightSystemEngineResolution:
assert runtime.memory_backend is backend
assert runtime._owns_memory_backend is True
+ def test_lightweight_system_carries_runtime_policy_and_limiter(self):
+ from openjarvis.server import agent_manager_routes as amr
+
+ policy = object()
+ limiter = object()
+ runtime = SimpleNamespace(
+ capability_policy=policy,
+ rate_limiter=limiter,
+ memory_backend=object(),
+ channel_backend=None,
+ channel_bridge=None,
+ knowledge_db_path=None,
+ )
+
+ system = amr._LightweightSystem(
+ engine=MagicMock(),
+ model="m",
+ config=SimpleNamespace(),
+ runtime=runtime,
+ )
+
+ assert system.capability_policy is policy
+ assert system.rate_limiter is limiter
+
def test_memory_backend_lazy_init_is_synchronized(self, monkeypatch):
pytest.importorskip("fastapi")
from openjarvis.server import agent_manager_routes as amr
diff --git a/tests/server/test_api_routes.py b/tests/server/test_api_routes.py
index f4e06eac..04913d84 100644
--- a/tests/server/test_api_routes.py
+++ b/tests/server/test_api_routes.py
@@ -9,6 +9,8 @@ fastapi = pytest.importorskip("fastapi")
from fastapi import FastAPI # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
+from openjarvis.core.events import EventBus, EventType # noqa: E402
+from openjarvis.security.capabilities import CapabilityPolicy # noqa: E402
from openjarvis.server.api_routes import ( # noqa: E402
include_all_routes,
memory_index,
@@ -44,6 +46,129 @@ class TestAgentRoutes:
resp = client.delete("/v1/agents/nonexistent")
assert resp.status_code in (404, 501)
+ def test_admin_lifecycle_is_capability_gated_before_mutation(self):
+ from openjarvis.tools.agent_tools import _SPAWNED_AGENTS
+
+ app = _make_app()
+ app.state.bus = EventBus(record_history=True)
+ app.state.capability_policy = CapabilityPolicy(default_deny=True)
+ app.state.rate_limiter = None
+ _SPAWNED_AGENTS.pop("forbidden-api-agent", None)
+
+ resp = TestClient(app).post(
+ "/v1/agents",
+ json={
+ "agent_type": "simple",
+ "agent_id": "forbidden-api-agent",
+ },
+ )
+
+ assert resp.status_code == 403
+ assert "forbidden-api-agent" not in _SPAWNED_AGENTS
+ denied = [
+ event
+ for event in app.state.bus.history
+ if event.event_type == EventType.CAPABILITY_DENIED
+ ]
+ assert denied[-1].data == {
+ "agent_id": "server:api",
+ "capability": "system:admin",
+ "tool": "agent_spawn",
+ }
+
+ def test_agent_listing_is_capability_gated_before_disclosure(self):
+ from openjarvis.tools.agent_tools import _SPAWNED_AGENTS
+
+ app = _make_app()
+ app.state.bus = EventBus(record_history=True)
+ app.state.capability_policy = CapabilityPolicy(default_deny=True)
+ app.state.rate_limiter = None
+ _SPAWNED_AGENTS["private-api-agent"] = {
+ "agent_id": "private-api-agent",
+ "agent_type": "simple",
+ "status": "running",
+ "created_at": 0.0,
+ }
+ try:
+ resp = TestClient(app).get("/v1/agents")
+ finally:
+ _SPAWNED_AGENTS.pop("private-api-agent", None)
+
+ assert resp.status_code == 403
+ assert "private-api-agent" not in resp.text
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data
+ == {
+ "agent_id": "server:api",
+ "capability": "system:admin",
+ "tool": "agent_list",
+ }
+ for event in app.state.bus.history
+ )
+
+ def test_admin_lifecycle_is_rate_limited_before_mutation(self):
+ from openjarvis.tools.agent_tools import _SPAWNED_AGENTS
+
+ class _DenyLimiter:
+ def __init__(self) -> None:
+ self.keys = []
+
+ def check(self, key: str):
+ self.keys.append(key)
+ return False, 2.5
+
+ app = _make_app()
+ app.state.bus = EventBus(record_history=True)
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("server:api", "system:admin")
+ limiter = _DenyLimiter()
+ app.state.capability_policy = policy
+ app.state.rate_limiter = limiter
+ _SPAWNED_AGENTS.pop("limited-api-agent", None)
+
+ resp = TestClient(app).post(
+ "/v1/agents",
+ json={"agent_type": "simple", "agent_id": "limited-api-agent"},
+ )
+
+ assert resp.status_code == 429
+ assert "limited-api-agent" not in _SPAWNED_AGENTS
+ assert limiter.keys == ["server:api:agent_spawn"]
+ assert any(
+ event.event_type == EventType.RATE_LIMITED
+ and event.data["agent_id"] == "server:api"
+ for event in app.state.bus.history
+ )
+
+ def test_agent_listing_is_rate_limited_before_disclosure(self):
+ class _DenyLimiter:
+ def __init__(self) -> None:
+ self.keys = []
+
+ def check(self, key: str):
+ self.keys.append(key)
+ return False, 2.5
+
+ app = _make_app()
+ app.state.bus = EventBus(record_history=True)
+ policy = CapabilityPolicy(default_deny=True)
+ policy.grant("server:api", "system:admin")
+ limiter = _DenyLimiter()
+ app.state.capability_policy = policy
+ app.state.rate_limiter = limiter
+
+ resp = TestClient(app).get("/v1/agents")
+
+ assert resp.status_code == 429
+ assert limiter.keys == ["server:api:agent_list"]
+ assert any(
+ event.event_type == EventType.RATE_LIMITED
+ and event.data["agent_id"] == "server:api"
+ and event.data["tool"] == "agent_list"
+ for event in app.state.bus.history
+ )
+
class TestMemoryRoutes:
# 503 is the documented response when the native ``openjarvis_rust``
diff --git a/tests/server/test_deep_research_tools_wiring.py b/tests/server/test_deep_research_tools_wiring.py
index 7c96d46c..a72188a2 100644
--- a/tests/server/test_deep_research_tools_wiring.py
+++ b/tests/server/test_deep_research_tools_wiring.py
@@ -17,8 +17,10 @@ except ImportError:
HAS_FASTAPI = False
from openjarvis.connectors.store import KnowledgeStore
+from openjarvis.core.events import EventBus
from openjarvis.core.registry import ToolRegistry
from openjarvis.core.types import Role, ToolResult
+from openjarvis.security.capabilities import CapabilityPolicy
from openjarvis.tools._stubs import BaseTool, ToolSpec
@@ -38,6 +40,7 @@ class _ConfiguredResearchProbe(BaseTool):
"properties": {"value": {"type": "string"}},
"required": ["value"],
},
+ required_capabilities=["system:admin"],
)
def execute(self, **params) -> ToolResult:
@@ -95,6 +98,15 @@ class _ScriptedDeepResearchEngine:
return {"content": "complete", "tool_calls": [], "usage": {}}
+class _RecordingRateLimiter:
+ def __init__(self) -> None:
+ self.keys: list[str] = []
+
+ def check(self, key: str):
+ self.keys.append(key)
+ return True, 0.0
+
+
@pytest.mark.skipif(not HAS_FASTAPI, reason="fastapi not installed")
def test_deep_research_agent_gets_tools(tmp_path: Path) -> None:
"""When knowledge.db exists, returns 4 tools."""
@@ -136,13 +148,14 @@ def test_deep_research_tools_returns_empty_when_no_db() -> None:
@pytest.mark.skipif(not HAS_FASTAPI, reason="fastapi not installed")
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "with_knowledge_db",
- [False, True],
- ids=["without-knowledge-db", "with-knowledge-db"],
+ "with_knowledge_db,deny_probe",
+ [(False, False), (True, False), (False, True)],
+ ids=["without-knowledge-db", "with-knowledge-db", "policy-denied"],
)
async def test_server_deep_research_merges_and_executes_all_tool_sources(
tmp_path: Path,
with_knowledge_db: bool,
+ deny_probe: bool,
monkeypatch,
) -> None:
"""Configured and MCP tools reach Deep Research with or without its DB."""
@@ -166,8 +179,17 @@ async def test_server_deep_research_merges_and_executes_all_tool_sources(
_ConfiguredResearchProbe.calls = 0
mcp_tool = _MCPResearchProbe()
+ runtime_agent_id = "agent-deep-research-682"
+ policy = None
+ if deny_probe:
+ policy = CapabilityPolicy(default_deny=True)
+ policy.deny(runtime_agent_id, "system:admin")
+ rate_limiter = _RecordingRateLimiter()
app_state = SimpleNamespace(
config=SimpleNamespace(memory_files=None, system_prompt=None),
+ bus=EventBus(record_history=True),
+ capability_policy=policy,
+ rate_limiter=rate_limiter,
memory_backend=None,
channel_backend=None,
channel_bridge=None,
@@ -186,7 +208,7 @@ async def test_server_deep_research_merges_and_executes_all_tool_sources(
response = await routes._stream_managed_agent(
manager=manager,
agent_record={
- "id": "agent-deep-research-682",
+ "id": runtime_agent_id,
"name": "Deep Research Agent",
"agent_type": "deep_research",
"config": {
@@ -228,8 +250,15 @@ async def test_server_deep_research_merges_and_executes_all_tool_sources(
assert not with_knowledge_db or knowledge_names.issubset(engine.advertised_names)
assert with_knowledge_db or knowledge_names.isdisjoint(engine.advertised_names)
assert engine.turns == 2
- assert _ConfiguredResearchProbe.calls == 1
- assert engine.observed_tool_result == "configured:sentinel"
+ assert _ConfiguredResearchProbe.calls == (0 if deny_probe else 1)
+ if deny_probe:
+ assert "system:admin" in engine.observed_tool_result
+ assert "denied" in engine.observed_tool_result
+ else:
+ assert engine.observed_tool_result == "configured:sentinel"
+ assert rate_limiter.keys == [
+ f"{runtime_agent_id}:{_ConfiguredResearchProbe.tool_id}"
+ ]
assert "data: [DONE]" in "".join(body_parts)
start_worker.assert_called_once()
assert start_worker.call_args.kwargs["name"].startswith(
@@ -239,11 +268,15 @@ async def test_server_deep_research_merges_and_executes_all_tool_sources(
manager.store_agent_response.assert_called_once()
stored = manager.store_agent_response.call_args
- assert stored.args[:2] == ("agent-deep-research-682", "complete")
+ assert stored.args[:2] == (runtime_agent_id, "complete")
persisted_calls = stored.kwargs["tool_calls"]
assert persisted_calls[0]["tool"] == _ConfiguredResearchProbe.tool_id
- assert persisted_calls[0]["result"] == "configured:sentinel"
- assert persisted_calls[0]["success"] is True
+ if deny_probe:
+ assert "system:admin" in persisted_calls[0]["result"]
+ assert persisted_calls[0]["success"] is False
+ else:
+ assert persisted_calls[0]["result"] == "configured:sentinel"
+ assert persisted_calls[0]["success"] is True
@pytest.mark.skipif(not HAS_FASTAPI, reason="fastapi not installed")
diff --git a/tests/server/test_routes.py b/tests/server/test_routes.py
index 27b7b694..fa3219f2 100644
--- a/tests/server/test_routes.py
+++ b/tests/server/test_routes.py
@@ -62,6 +62,9 @@ def _test_config():
cfg = JarvisConfig()
cfg.analytics.enabled = False
cfg.traces.enabled = False
+ # Route tests exercise the injected engine directly. Factory-level
+ # config-derived security is covered separately.
+ cfg.security.enabled = False
return cfg
@@ -233,6 +236,78 @@ class TestMemoryServiceWiring:
class TestChatCompletions:
+ def test_server_agent_cannot_use_default_grant_after_explicit_deny(self):
+ from openjarvis.agents.orchestrator import OrchestratorAgent
+ from openjarvis.core.types import ToolResult
+ from openjarvis.tools._stubs import BaseTool, ToolSpec
+
+ class _PrivilegedTool(BaseTool):
+ tool_id = "server_privileged_probe"
+ calls = 0
+
+ @property
+ def spec(self):
+ return ToolSpec(
+ name=self.tool_id,
+ description="Must remain blocked",
+ required_capabilities=["code:execute"],
+ )
+
+ def execute(self, **params):
+ type(self).calls += 1
+ return ToolResult(tool_name=self.tool_id, content="unsafe")
+
+ class _DenyPolicy:
+ def check(self, agent_id, capability, resource=""):
+ assert agent_id == "server-agent"
+ assert capability == "code:execute"
+ return False
+
+ engine = _make_engine()
+ engine.generate.side_effect = [
+ {
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "call-denied",
+ "name": _PrivilegedTool.tool_id,
+ "arguments": "{}",
+ }
+ ],
+ "finish_reason": "tool_calls",
+ },
+ {"content": "request safely refused", "finish_reason": "stop"},
+ ]
+ bus = EventBus(record_history=True)
+ agent = OrchestratorAgent(
+ engine,
+ "test-model",
+ tools=[_PrivilegedTool()],
+ bus=bus,
+ capability_policy=_DenyPolicy(),
+ agent_id="server-agent",
+ parallel_tools=False,
+ )
+ client = TestClient(
+ create_app(
+ engine, "test-model", agent=agent, bus=bus, config=_test_config()
+ )
+ )
+
+ response = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "test-model",
+ "messages": [{"role": "user", "content": "run privileged probe"}],
+ },
+ )
+
+ assert response.status_code == 200
+ assert _PrivilegedTool.calls == 0
+ denied = [e for e in bus.history if e.event_type == EventType.CAPABILITY_DENIED]
+ assert len(denied) == 1
+ assert denied[0].data["agent_id"] == "server-agent"
+
def test_basic_completion(self, client):
resp = client.post(
"/v1/chat/completions",
diff --git a/tests/server/test_security_factory_wiring.py b/tests/server/test_security_factory_wiring.py
new file mode 100644
index 00000000..0f3a643a
--- /dev/null
+++ b/tests/server/test_security_factory_wiring.py
@@ -0,0 +1,279 @@
+"""Adversarial security wiring tests for the programmatic app factory."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+
+pytest.importorskip("fastapi")
+
+from openjarvis.core.config import JarvisConfig
+from openjarvis.core.events import EventBus, EventType
+from openjarvis.security import SecurityContext
+from openjarvis.security.capabilities import CapabilityPolicy
+from openjarvis.server.app import create_app
+
+
+def _config() -> JarvisConfig:
+ config = JarvisConfig()
+ config.analytics.enabled = False
+ config.traces.enabled = False
+ config.security.enabled = True
+ return config
+
+
+def _runtime_config() -> JarvisConfig:
+ """Factory config without external analytics or derived security."""
+ config = JarvisConfig()
+ config.analytics.enabled = False
+ config.traces.enabled = False
+ config.security.enabled = False
+ return config
+
+
+def test_factory_derives_missing_security_and_secures_prebuilt_agent(
+ monkeypatch,
+) -> None:
+ engine = MagicMock(name="raw-engine")
+ wrapped = MagicMock(name="wrapped-engine")
+ policy = object()
+ limiter = object()
+ audit = object()
+ setup = MagicMock(
+ return_value=SecurityContext(
+ engine=wrapped,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ audit_logger=audit,
+ )
+ )
+ monkeypatch.setattr("openjarvis.security.setup_security", setup)
+ agent = SimpleNamespace(
+ agent_id="tool-agent",
+ _engine=engine,
+ _executor=SimpleNamespace(
+ _capability_policy=None,
+ _rate_limiter=None,
+ _agent_id="",
+ ),
+ )
+
+ app = create_app(engine, "model", agent=agent, config=_config())
+
+ setup.assert_called_once()
+ assert app.state.engine is wrapped
+ assert app.state.bus is not None
+ assert app.state.capability_policy is policy
+ assert app.state.rate_limiter is limiter
+ assert app.state.audit_logger is audit
+ assert agent._engine is wrapped
+ assert agent._bus is app.state.bus
+ assert agent._executor._bus is app.state.bus
+ assert agent._executor._capability_policy is policy
+ assert agent._executor._rate_limiter is limiter
+ assert agent._executor._agent_id == "tool-agent"
+
+
+def test_factory_preserves_explicit_security_primitives(monkeypatch) -> None:
+ derived_policy = object()
+ derived_limiter = object()
+ derived_audit = object()
+ explicit_policy = object()
+ explicit_limiter = object()
+ setup = MagicMock(
+ return_value=SecurityContext(
+ engine="wrapped",
+ capability_policy=derived_policy,
+ rate_limiter=derived_limiter,
+ audit_logger=derived_audit,
+ )
+ )
+ monkeypatch.setattr("openjarvis.security.setup_security", setup)
+
+ app = create_app(
+ "raw",
+ "model",
+ config=_config(),
+ capability_policy=explicit_policy,
+ rate_limiter=explicit_limiter,
+ )
+
+ assert app.state.engine == "wrapped"
+ assert app.state.capability_policy is explicit_policy
+ assert app.state.rate_limiter is explicit_limiter
+ assert app.state.audit_logger is derived_audit
+
+
+def test_factory_propagates_strict_security_setup_failure(monkeypatch) -> None:
+ monkeypatch.setattr(
+ "openjarvis.security.setup_security",
+ MagicMock(side_effect=RuntimeError("policy failed")),
+ )
+
+ with pytest.raises(RuntimeError, match="policy failed"):
+ create_app("raw", "model", config=_config())
+
+
+def test_factory_synchronizes_prebuilt_rlm_lazy_executor_runtime(monkeypatch) -> None:
+ from openjarvis.agents.rlm import RLMAgent
+ from openjarvis.agents.rlm_repl import RLMRepl
+
+ engine = MagicMock()
+ engine.generate.side_effect = [
+ {"content": "```python\nsentinel = 42\n```", "finish_reason": "stop"},
+ {"content": "finished", "finish_reason": "stop"},
+ ]
+ bus = EventBus(record_history=True)
+ policy = CapabilityPolicy(default_deny=True)
+ # Permit the top-level agent gate, but not the lazily-created REPL tool.
+ policy.grant("server-rlm", "code:execute", "agent_run")
+
+ class _Limiter:
+ def __init__(self):
+ self.keys = []
+
+ def check(self, key):
+ self.keys.append(key)
+ return True, 0.0
+
+ limiter = _Limiter()
+ agent = RLMAgent(engine, "model")
+ repl_execute = MagicMock(return_value="should not execute")
+ monkeypatch.setattr(RLMRepl, "execute", repl_execute)
+
+ app = create_app(
+ engine,
+ "model",
+ agent=agent,
+ agent_name="server-rlm",
+ bus=bus,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ config=_runtime_config(),
+ )
+ result = app.state.agent.run("execute generated code")
+
+ assert result.content == "finished"
+ repl_execute.assert_not_called()
+ assert agent._runtime_bus is bus
+ assert agent._runtime_capability_policy is policy
+ assert agent._runtime_rate_limiter is limiter
+ assert agent._runtime_agent_id == "server-rlm"
+ assert limiter.keys == [
+ "server-rlm:agent_run",
+ "server-rlm:rlm_repl",
+ ]
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data
+ == {
+ "agent_id": "server-rlm",
+ "capability": "code:execute",
+ "tool": "rlm_repl",
+ }
+ for event in bus.history
+ )
+
+
+def test_factory_preserves_prebuilt_rlm_policy_and_limiter_while_reidentifying() -> (
+ None
+):
+ from openjarvis.agents.rlm import RLMAgent
+
+ engine = MagicMock()
+ agent_policy = CapabilityPolicy(default_deny=True)
+ server_policy = CapabilityPolicy(default_deny=True)
+ agent_limiter = object()
+ server_limiter = object()
+ agent = RLMAgent(
+ engine,
+ "model",
+ capability_policy=agent_policy,
+ rate_limiter=agent_limiter,
+ agent_id="prebuilt-id",
+ )
+
+ create_app(
+ engine,
+ "model",
+ agent=agent,
+ agent_name="server-id",
+ capability_policy=server_policy,
+ rate_limiter=server_limiter,
+ config=_runtime_config(),
+ )
+
+ assert agent._capability_policy is agent_policy
+ assert agent._runtime_capability_policy is agent_policy
+ assert agent._rate_limiter is agent_limiter
+ assert agent._runtime_rate_limiter is agent_limiter
+ assert agent._runtime_agent_id == "server-id"
+
+
+def test_factory_overrides_prebuilt_executor_identity_at_server_boundary() -> None:
+ from openjarvis.agents.orchestrator import OrchestratorAgent
+ from openjarvis.core.types import ToolCall, ToolResult
+ from openjarvis.tools._stubs import BaseTool, ToolSpec
+
+ class _AdminTool(BaseTool):
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name="tenant_admin_probe",
+ description="Identity regression probe.",
+ required_capabilities=["system:admin"],
+ )
+
+ def execute(self, **params) -> ToolResult:
+ return ToolResult(tool_name=self.spec.name, content="executed")
+
+ engine = MagicMock()
+ bus = EventBus(record_history=True)
+ policy = CapabilityPolicy(default_deny=True)
+ # This grant demonstrates the bypass: the prebuilt class-default identity
+ # is privileged, while the identity assigned by the server is not.
+ policy.grant("orchestrator", "system:admin", "tenant_admin_probe")
+ agent = OrchestratorAgent(engine, "model", tools=[_AdminTool()])
+ assert agent._executor._agent_id == "orchestrator"
+
+ create_app(
+ engine,
+ "model",
+ agent=agent,
+ agent_name="tenant-denied",
+ bus=bus,
+ capability_policy=policy,
+ config=_runtime_config(),
+ )
+ result = agent._executor.execute(
+ ToolCall(id="identity-probe", name="tenant_admin_probe", arguments="{}")
+ )
+
+ assert not result.success
+ assert "system:admin" in result.content
+ assert agent._runtime_agent_id == "tenant-denied"
+ assert agent._executor._agent_id == "tenant-denied"
+ assert any(
+ event.event_type == EventType.CAPABILITY_DENIED
+ and event.data
+ == {
+ "agent_id": "tenant-denied",
+ "capability": "system:admin",
+ "tool": "tenant_admin_probe",
+ }
+ for event in bus.history
+ )
+
+
[email protected]("profile", ["", "personal", "shared", "server"])
+def test_factory_rejects_invalid_enabled_policy_in_every_profile(tmp_path, profile):
+ config = _config()
+ config.security.profile = profile
+ config.security.capabilities.enabled = True
+ path = tmp_path / "invalid-policy.json"
+ path.write_text("{invalid}")
+ config.security.capabilities.policy_path = str(path)
+ with pytest.raises(RuntimeError, match="Capability policy initialization"):
+ create_app(MagicMock(), "model", config=config)
diff --git a/tests/test_orchestrator_learning/test_environment.py b/tests/test_orchestrator_learning/test_environment.py
index bcce6ac2..f91d6cd6 100644
--- a/tests/test_orchestrator_learning/test_environment.py
+++ b/tests/test_orchestrator_learning/test_environment.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import pytest
+from openjarvis.core.events import EventBus, EventType
from openjarvis.core.types import ToolResult
from openjarvis.learning.intelligence.orchestrator.environment import (
OrchestratorEnvironment,
@@ -50,10 +51,122 @@ class _MockCalculator(BaseTool):
)
+class _ProbeTool(BaseTool):
+ tool_id = "probe"
+
+ def __init__(self, name: str, capabilities: list[str]) -> None:
+ self._name = name
+ self._capabilities = capabilities
+ self.executed = False
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name=self._name,
+ description="learning security enforcement probe",
+ required_capabilities=self._capabilities,
+ )
+
+ def execute(self, **params) -> ToolResult:
+ self.executed = True
+ return ToolResult(tool_name=self._name, content="executed", success=True)
+
+
+class _DenyPolicy:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, str, str]] = []
+
+ def check(self, agent_id: str, capability: str, resource: str) -> bool:
+ self.calls.append((agent_id, capability, resource))
+ return False
+
+
+class _RecordingLimiter:
+ def __init__(self, allowed: bool = True) -> None:
+ self.allowed = allowed
+ self.keys: list[str] = []
+
+ def check(self, key: str) -> tuple[bool, float]:
+ self.keys.append(key)
+ return self.allowed, 1.0 if not self.allowed else 0.0
+
+
# -- Tests -------------------------------------------------------------------
class TestOrchestratorEnvironment:
+ def test_admin_capability_is_fail_closed_and_auditable(self):
+ tool = _ProbeTool("admin_probe", ["system:admin"])
+ policy = _DenyPolicy()
+ limiter = _RecordingLimiter()
+ bus = EventBus(record_history=True)
+ env = OrchestratorEnvironment(
+ tools=[tool],
+ bus=bus,
+ capability_policy=policy,
+ rate_limiter=limiter,
+ )
+
+ state = env.reset("probe")
+ _, observation = env.step(
+ state,
+ OrchestratorAction(
+ thought="probe",
+ tool_name="admin_probe",
+ tool_input="{}",
+ ),
+ )
+
+ assert "system:admin" in observation.content
+ assert tool.executed is False
+ assert limiter.keys == ["learning:admin_probe"]
+ assert policy.calls == [("learning", "system:admin", "admin_probe")]
+ denied = [
+ event
+ for event in bus.history
+ if event.event_type == EventType.CAPABILITY_DENIED
+ ]
+ assert len(denied) == 1
+ assert denied[0].data["agent_id"] == "learning"
+
+ def test_canonical_capability_cannot_be_removed_in_learning_path(self):
+ tool = _ProbeTool("channel_send", [])
+ policy = _DenyPolicy()
+ env = OrchestratorEnvironment(tools=[tool], capability_policy=policy)
+
+ state = env.reset("probe")
+ _, observation = env.step(
+ state,
+ OrchestratorAction(
+ thought="probe",
+ tool_name="channel_send",
+ tool_input="{}",
+ ),
+ )
+
+ assert "channel:send" in observation.content
+ assert tool.executed is False
+ assert policy.calls == [("learning", "channel:send", "channel_send")]
+
+ def test_rate_limit_is_fail_closed_before_learning_dispatch(self):
+ tool = _ProbeTool("admin_probe", ["system:admin"])
+ limiter = _RecordingLimiter(allowed=False)
+ env = OrchestratorEnvironment(tools=[tool], rate_limiter=limiter)
+
+ state = env.reset("probe")
+ _, observation = env.step(
+ state,
+ OrchestratorAction(
+ thought="probe",
+ tool_name="admin_probe",
+ tool_input="{}",
+ ),
+ )
+
+ assert "Rate limit exceeded" in observation.content
+ assert limiter.keys == ["learning:admin_probe"]
+ assert tool.executed is False
+
def test_reset_creates_clean_state(self):
env = OrchestratorEnvironment(tools=[_MockCalculator()])
state = env.reset("What is 2+2?")
diff --git a/tests/tools/test_stubs.py b/tests/tools/test_stubs.py
index 377d1566..a1c983a8 100644
--- a/tests/tools/test_stubs.py
+++ b/tests/tools/test_stubs.py
@@ -8,7 +8,9 @@ import pytest
from openjarvis.core.events import EventBus, EventType
from openjarvis.core.types import ToolCall, ToolResult
+from openjarvis.security.capabilities import DEFAULT_TOOL_CAPABILITIES
from openjarvis.tools._stubs import BaseTool, ToolExecutor, ToolSpec
+from openjarvis.tools.code_interpreter import CodeInterpreterTool
# ---------------------------------------------------------------------------
# Helpers
@@ -65,6 +67,42 @@ class _ScalarBoundaryGuard:
)
+class _NamedTool(BaseTool):
+ """Tool with caller-controlled metadata for capability-policy tests."""
+
+ def __init__(self, name: str, required_capabilities=None) -> None:
+ self.tool_id = name
+ self._required_capabilities = required_capabilities or []
+ self.calls = 0
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name=self.tool_id,
+ description="Capability test tool.",
+ required_capabilities=self._required_capabilities,
+ )
+
+ def execute(self, **params) -> ToolResult:
+ self.calls += 1
+ return ToolResult(tool_name=self.tool_id, content="executed")
+
+
+class _RecordingPolicy:
+ def __init__(self, allowed=()) -> None:
+ self.allowed = set(allowed)
+ self.checks = []
+
+ def check(self, agent_id, capability, resource="") -> bool:
+ self.checks.append((agent_id, capability, resource))
+ return capability in self.allowed
+
+
+class _FalseyDenyAllPolicy(_RecordingPolicy):
+ def __bool__(self) -> bool:
+ return False
+
+
# ---------------------------------------------------------------------------
# ToolSpec tests
# ---------------------------------------------------------------------------
@@ -127,6 +165,82 @@ class TestBaseTool:
class TestToolExecutor:
+ def test_default_deny_blocks_code_interpreter_without_declared_capability(self):
+ policy = _RecordingPolicy()
+ tool = CodeInterpreterTool()
+ assert tool.spec.required_capabilities == []
+ executor = ToolExecutor([tool], capability_policy=policy, agent_id="deny-all")
+
+ result = executor.execute(
+ ToolCall(
+ id="1",
+ name="code_interpreter",
+ arguments='{"code":"print(6 * 7)"}',
+ )
+ )
+
+ assert result.success is False
+ assert "Capability 'code:execute' denied" in result.content
+ assert policy.checks == [("deny-all", "code:execute", "code_interpreter")]
+
+ @pytest.mark.parametrize(
+ ("tool_name", "canonical_capabilities"),
+ list(DEFAULT_TOOL_CAPABILITIES.items()),
+ )
+ def test_every_canonical_tool_capability_is_enforced(
+ self, tool_name, canonical_capabilities
+ ):
+ tool = _NamedTool(tool_name)
+ policy = _RecordingPolicy()
+ executor = ToolExecutor([tool], capability_policy=policy, agent_id="deny-all")
+
+ result = executor.execute(ToolCall(id="1", name=tool_name, arguments="{}"))
+
+ if not canonical_capabilities:
+ # A reviewed-safe canonical name is safe only for its in-tree
+ # implementation. This foreign-provenance test double must not
+ # be able to impersonate calculator/think and bypass policy.
+ assert result.success is False
+ assert tool.calls == 0
+ assert policy.checks == [
+ ("deny-all", "system:admin", tool_name),
+ ]
+ return
+
+ expected = canonical_capabilities[0].value
+ assert result.success is False
+ assert tool.calls == 0
+ assert policy.checks == [("deny-all", expected, tool_name)]
+
+ def test_declared_capability_cannot_replace_canonical_security_floor(self):
+ tool = _NamedTool("code_interpreter", ["file:read"])
+ policy = _RecordingPolicy(allowed={"file:read"})
+ executor = ToolExecutor([tool], capability_policy=policy, agent_id="limited")
+
+ result = executor.execute(
+ ToolCall(id="1", name="code_interpreter", arguments="{}")
+ )
+
+ assert result.success is False
+ assert tool.calls == 0
+ assert policy.checks == [
+ ("limited", "file:read", "code_interpreter"),
+ ("limited", "code:execute", "code_interpreter"),
+ ]
+
+ def test_falsey_policy_object_cannot_bypass_enforcement(self):
+ tool = _NamedTool("code_interpreter")
+ policy = _FalseyDenyAllPolicy()
+ executor = ToolExecutor([tool], capability_policy=policy, agent_id="deny-all")
+
+ result = executor.execute(
+ ToolCall(id="1", name="code_interpreter", arguments="{}")
+ )
+
+ assert result.success is False
+ assert tool.calls == 0
+ assert policy.checks == [("deny-all", "code:execute", "code_interpreter")]
+
def test_execute_success(self):
executor = ToolExecutor([_EchoTool()])
call = ToolCall(id="1", name="echo", arguments='{"text":"hi"}')