Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(agent): fork_once keeps middleware tools in schema, denies at runtime

xf gong33bdc870cd64
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index 52fd6da..e1d0df1 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -25,6 +25,7 @@ from cubepi.agent.types import (
AgentEndEvent,
AgentEvent,
AgentTool,
+ AgentToolResult,
ForkOnceResult,
MessageEndEvent,
MessageStartEvent,
@@ -54,6 +55,31 @@ if TYPE_CHECKING:
from cubepi.providers.fallback import FallbackBoundModel
+def _deny_in_fork(tool: AgentTool) -> AgentTool:
+ """Return a copy of *tool* whose execute always returns an error.
+
+ Used by fork_once to keep middleware tools in the schema (prompt-cache
+ parity) while preventing execution that would mutate parent state.
+ """
+ from dataclasses import replace
+
+ async def _denied(
+ tool_call_id: str,
+ args: object,
+ *,
+ signal: asyncio.Event | None = None,
+ on_update: Callable | None = None,
+ ) -> AgentToolResult:
+ return AgentToolResult(
+ content=[
+ TextContent(text=f"{tool.name} is not available in a forked agent.")
+ ],
+ is_error=True,
+ )
+
+ return replace(tool, execute=_denied)
+
+
def _default_convert_to_llm(
messages: list[Message], *, ctx: AgentContext
) -> list[Message]:
@@ -537,12 +563,15 @@ class Agent(Generic[TMessage]):
# middleware twice — the parent's composed result already lives on
# self.transform_context etc.
#
- # Strip middleware-owned tools (e.g. expand_tools) — their execute
- # callbacks close over the parent's state and would corrupt it.
+ # Keep middleware-owned tools in the schema (prompt-cache parity)
+ # but deny their execution at runtime — their execute callbacks
+ # close over the parent's state and would corrupt it.
_mw_tool_ids = {
id(t) for mw in self._middleware for t in getattr(mw, "tools", []) or []
}
- fork_tools = [t for t in self._state.tools if id(t) not in _mw_tool_ids]
+ fork_tools = [
+ _deny_in_fork(t) if id(t) in _mw_tool_ids else t for t in self._state.tools
+ ]
child: Agent = Agent(
model=self._model,
system_prompt=self._state.system_prompt,
diff --git a/tests/deferred/test_agent_wiring.py b/tests/deferred/test_agent_wiring.py
index 677dac9..3b6b54b 100644
--- a/tests/deferred/test_agent_wiring.py
+++ b/tests/deferred/test_agent_wiring.py
@@ -135,8 +135,11 @@ class TestAgentDeferredToolGroups:
assert deferred_mw._on_tools_expanded is not None
-class TestForkOnceStripsMiddlewareTools:
- def test_fork_tools_exclude_expand_tools(self) -> None:
+class TestForkOnceDeniesMiddlewareTools:
+ def test_fork_keeps_expand_tools_in_schema(self) -> None:
+ """expand_tools stays in the tool list for prompt-cache parity."""
+ from cubepi.agent.agent import _deny_in_fork
+
model = _make_faux_model()
group = _make_group("mcp:github", ["t1", "t2"])
agent = Agent(
@@ -144,11 +147,29 @@ class TestForkOnceStripsMiddlewareTools:
tools=[_dummy_tool("builtin")],
deferred_tool_groups=[group],
)
- # Collect middleware tool ids.
mw_tool_ids = {
id(t) for mw in agent._middleware for t in getattr(mw, "tools", []) or []
}
- fork_tools = [t for t in agent._state.tools if id(t) not in mw_tool_ids]
+ fork_tools = [
+ _deny_in_fork(t) if id(t) in mw_tool_ids else t for t in agent._state.tools
+ ]
fork_tool_names = [t.name for t in fork_tools]
assert "builtin" in fork_tool_names
- assert "expand_tools" not in fork_tool_names
+ assert "expand_tools" in fork_tool_names
+
+ async def test_fork_expand_tools_returns_error(self) -> None:
+ """expand_tools in fork returns is_error=True instead of executing."""
+ from cubepi.agent.agent import _deny_in_fork
+
+ model = _make_faux_model()
+ group = _make_group("mcp:github", ["t1"])
+ agent = Agent(
+ model=model,
+ deferred_tool_groups=[group],
+ )
+ expand_tool = next(t for t in agent._state.tools if t.name == "expand_tools")
+ denied = _deny_in_fork(expand_tool)
+ assert denied.name == "expand_tools"
+ result = await denied.execute("call-1", _Empty())
+ assert result.is_error is True
+ assert "not available in a forked agent" in result.content[0].text