Skip to content

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

fix(subagents): also drill into middleware.tools when stripping HITL

xf gongdb394e619c4b
diff --git a/cubepi/middleware/subagents.py b/cubepi/middleware/subagents.py
index 3211e76..aae537f 100644
--- a/cubepi/middleware/subagents.py
+++ b/cubepi/middleware/subagents.py
@@ -22,19 +22,47 @@ EventMapper = Callable[[AgentEvent], Sequence[StructuredValue] | StructuredValue
EventHandler = Callable[[str, StructuredValue], Awaitable[None] | None]
+def _is_checkpointed_hitl(x: object) -> bool:
+ """True if ``x.hitl`` is a checkpointed ``HitlBinding``."""
+ binding = getattr(x, "hitl", None)
+ return binding is not None and bool(getattr(binding, "checkpointed", False))
+
+
def _drop_checkpointed_hitl(items: Sequence) -> list:
- """Remove elements whose ``.hitl`` is a checkpointed binding.
+ """Remove elements that carry — or expose — a checkpointed HITL binding.
Used by ``SubagentMiddleware`` to keep parent-bound HITL state out of an
- ephemeral child agent — the child has its own run_id, but a checkpointed
- ``HitlBinding`` carries the parent's run_id, which ``Agent._validate_hitl
- _bindings`` rejects at ``prompt()`` entry. Elements without ``.hitl`` (or
- with a non-checkpointed binding) pass through untouched.
+ ephemeral child agent. The child has its own run_id, but a checkpointed
+ ``HitlBinding`` carries the parent's run_id, which
+ ``Agent._validate_hitl_bindings`` rejects at ``prompt()`` entry.
+
+ Two ways an element can introduce parent-bound HITL into the child:
+
+ * The element itself has ``.hitl`` set (an ``AgentTool`` like
+ ``ask_user_tool(...)`` or a middleware like
+ ``ApprovalPolicyMiddleware``). Dropped directly.
+ * A middleware that doesn't carry ``.hitl`` itself but exposes
+ ``.tools`` containing an HITL-checkpointed tool — ``Agent.__init__``
+ appends ``getattr(mw, "tools", [])`` to ``state.tools`` and the
+ validator would still see the parent-bound tool there. The whole
+ middleware is dropped in this case; constructing a tools-filtered
+ proxy would break ``compose_middleware._has_method`` (it does
+ ``type(mw)`` lookups), so dropping the unit is the simpler and
+ type-safe option. Trade-off: any non-HITL hooks on that middleware
+ are also lost in the subagent — by packaging HITL tools inside a
+ middleware the host has effectively declared the middleware to be
+ an HITL unit.
+
+ Elements without ``.hitl`` (or with a non-checkpointed binding) and
+ with no checkpointed-HITL tools inside their ``.tools`` attribute
+ pass through untouched.
"""
out: list = []
for x in items:
- binding = getattr(x, "hitl", None)
- if binding is not None and getattr(binding, "checkpointed", False):
+ if _is_checkpointed_hitl(x):
+ continue
+ nested_tools = getattr(x, "tools", None)
+ if nested_tools and any(_is_checkpointed_hitl(t) for t in nested_tools):
continue
out.append(x)
return out
diff --git a/tests/middleware/test_subagents.py b/tests/middleware/test_subagents.py
index c698425..6500448 100644
--- a/tests/middleware/test_subagents.py
+++ b/tests/middleware/test_subagents.py
@@ -566,3 +566,73 @@ async def test_subagent_strips_checkpointed_hitl_bound_tools() -> None:
await parent.prompt("dispatch the subagent")
assert parent.state.error_message is None
+
+
+async def test_subagent_strips_middleware_exposing_checkpointed_hitl_tools() -> None:
+ """A custom middleware that itself has no ``.hitl`` but exposes a
+ checkpointed-HITL tool via its ``.tools`` attribute must NOT reach the
+ child agent — ``Agent.__init__`` would otherwise append that tool to
+ ``state.tools`` and the child's ``prompt()`` would fail with the same
+ ``checkpointed HITL elements bound to run_ids`` error this fix is meant
+ to avoid (codex P2 on PR #159).
+ """
+ from cubepi.hitl.binding import HitlBinding
+ from cubepi.middleware.base import Middleware
+
+ class _NoOpParams(BaseModel):
+ pass
+
+ async def _noop_exec(
+ call_id: str, args: _NoOpParams, *, signal=None, on_update=None
+ ) -> AgentToolResult:
+ del call_id, args, signal, on_update
+ return AgentToolResult(content=[TextContent(text="noop")])
+
+ parent_bound_tool = AgentTool(
+ name="parent_hitl_tool",
+ description="HITL tool inside a custom middleware",
+ parameters=_NoOpParams,
+ execute=_noop_exec,
+ hitl=HitlBinding(checkpointed=True, run_id="parent-run-zzz"),
+ )
+
+ class _HitlPackagingMiddleware(Middleware):
+ def __init__(self) -> None:
+ self.tools = [parent_bound_tool]
+
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses([faux_assistant_message("done")])
+
+ middleware = _make_middleware(
+ provider=provider,
+ inherited_middleware=[_HitlPackagingMiddleware()],
+ )
+
+ parent_provider = FauxProvider(provider_id="faux")
+ parent_provider.set_responses(
+ [
+ faux_assistant_message(
+ [
+ faux_tool_call(
+ "subagent",
+ {"name": "n", "role": "r", "task": "t", "prompt": "p"},
+ )
+ ],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("done"),
+ ]
+ )
+ parent = Agent(
+ model=parent_provider.model("faux-1"),
+ system_prompt="parent",
+ tools=middleware.tools,
+ middleware=[middleware],
+ )
+
+ # Without the .tools drill-in, the wrapping middleware passes the strip
+ # and ``Agent.__init__`` lifts ``parent_hitl_tool`` into the child's
+ # ``state.tools`` — child ``prompt()`` then raises.
+ await parent.prompt("dispatch the subagent")
+
+ assert parent.state.error_message is None