Skip to content

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

feat(hitl): ApprovalPolicyMiddleware, ConfirmToolCallMiddleware, ask_user tool

xf gong785cc23d212d
diff --git a/cubepi/hitl/__init__.py b/cubepi/hitl/__init__.py
index bebaf2f..b7953b2 100644
--- a/cubepi/hitl/__init__.py
+++ b/cubepi/hitl/__init__.py
@@ -23,6 +23,9 @@ from cubepi.hitl.policy import (
AskUser,
Deny,
)
+from cubepi.hitl.ask_user import AskUserParams, ask_user_tool
+from cubepi.hitl.channel import HitlChannel, InMemoryChannel
+from cubepi.hitl.middleware import ApprovalPolicyMiddleware, ConfirmToolCallMiddleware
from cubepi.hitl.types import (
ApproveAnswer,
ApproveRequest,
@@ -62,4 +65,13 @@ __all__ = [
"HitlNoPendingRequest",
"HitlStaleAnswer",
"HitlTimedOut",
+ # ask_user
+ "AskUserParams",
+ "ask_user_tool",
+ # channel
+ "HitlChannel",
+ "InMemoryChannel",
+ # middleware
+ "ApprovalPolicyMiddleware",
+ "ConfirmToolCallMiddleware",
]
diff --git a/cubepi/hitl/ask_user.py b/cubepi/hitl/ask_user.py
new file mode 100644
index 0000000..4d38be6
--- /dev/null
+++ b/cubepi/hitl/ask_user.py
@@ -0,0 +1,90 @@
+from __future__ import annotations
+
+import json
+
+from pydantic import BaseModel
+
+from cubepi.agent.types import AgentTool, AgentToolResult
+from cubepi.hitl.channel import HitlChannel
+from cubepi.hitl.types import Option, Question
+from cubepi.providers.base import TextContent
+
+
+class _OptionDef(BaseModel):
+ label: str
+ value: str
+ description: str | None = None
+ allow_input: bool = False
+
+
+class _QuestionDef(BaseModel):
+ key: str
+ prompt: str
+ options: list[_OptionDef] | None = None
+ multi_select: bool = False
+ required: bool = True
+
+
+class AskUserParams(BaseModel):
+ questions: list[_QuestionDef]
+
+
+_DESCRIPTION = (
+ "Ask the user one or more structured questions. Use ONLY when you need "
+ "a specific selection or piece of info to proceed; for free-form clarification, "
+ "just end your turn with the question as text — the user's next message will be the answer."
+)
+
+
+def _format_answers(answers: dict) -> str:
+ return "User answers:\n" + json.dumps(answers, indent=2, ensure_ascii=False)
+
+
+def ask_user_tool(channel: HitlChannel) -> AgentTool:
+ async def execute(
+ call_id: str, args: AskUserParams, *, signal=None, on_update=None
+ ) -> AgentToolResult:
+ from cubepi.hitl.exceptions import HitlCancelled, HitlTimedOut
+
+ questions = [
+ Question(
+ key=q.key,
+ prompt=q.prompt,
+ options=[Option(**o.model_dump()) for o in q.options]
+ if q.options
+ else None,
+ multi_select=q.multi_select,
+ required=q.required,
+ )
+ for q in args.questions
+ ]
+ # Per spec §7: cancel/timeout in ask_user context surface as
+ # tool_result.is_error=True so the model can react. Other HITL control
+ # exceptions (HitlDetached, HitlAborted) DO propagate — those signal
+ # whole-agent state changes that must reach the loop's outer catch.
+ try:
+ answers = await channel.ask(questions, signal=signal)
+ except HitlCancelled as exc:
+ return AgentToolResult(
+ content=[TextContent(text=f"cancelled by user: {exc.reason}")],
+ details={"hitl": {"outcome": "cancelled", "reason": exc.reason}},
+ is_error=True,
+ )
+ except HitlTimedOut as exc:
+ return AgentToolResult(
+ content=[TextContent(text=f"timed out after {exc.seconds} seconds")],
+ details={"hitl": {"outcome": "timed_out", "seconds": exc.seconds}},
+ is_error=True,
+ )
+ return AgentToolResult(
+ content=[TextContent(text=_format_answers(answers))],
+ details={"hitl": {"kind": "ask", "answers": answers}},
+ )
+
+ return AgentTool(
+ name="ask_user",
+ description=_DESCRIPTION,
+ parameters=AskUserParams,
+ execute=execute,
+ execution_mode="sequential",
+ )
diff --git a/cubepi/hitl/middleware.py b/cubepi/hitl/middleware.py
new file mode 100644
index 0000000..2590fb6
--- /dev/null
+++ b/cubepi/hitl/middleware.py
@@ -0,0 +1,134 @@
+from __future__ import annotations
+
+import inspect
+from typing import Any, Awaitable, Callable, Iterable, Union
+
+from cubepi.agent.types import BeforeToolCallContext, BeforeToolCallResult
+from cubepi.hitl.channel import HitlChannel
+from cubepi.hitl.exceptions import HitlCancelled, HitlTimedOut
+from cubepi.hitl.policy import Approve, ApprovalDecision, AskUser, Deny
+from cubepi.middleware.base import Middleware
+
+
+def _args_to_dict(args: Any) -> dict:
+ if hasattr(args, "model_dump"):
+ return args.model_dump()
+ if isinstance(args, dict):
+ return dict(args)
+ return dict(vars(args))
+
+
+class ApprovalPolicyMiddleware(Middleware):
+ def __init__(
+ self,
+ channel: HitlChannel,
+ policy: Callable[
+ [BeforeToolCallContext],
+ Union[ApprovalDecision, Awaitable[ApprovalDecision]],
+ ],
+ ):
+ self._channel = channel
+ self._policy = policy
+
+ async def before_tool_call(self, ctx, *, signal=None):
+ decision = self._policy(ctx)
+ if inspect.isawaitable(decision):
+ decision = await decision
+
+ if isinstance(decision, Approve):
+ return None
+
+ if isinstance(decision, Deny):
+ return BeforeToolCallResult(
+ block=True,
+ deny_reason=decision.reason,
+ reason=decision.reason,
+ hitl_trace={"decision": "policy_deny", "reason": decision.reason},
+ )
+
+ if isinstance(decision, AskUser):
+ return await self._ask_and_translate(ctx, decision, signal=signal)
+
+ raise TypeError(f"policy returned unexpected {type(decision).__name__}")
+
+ async def _ask_and_translate(self, ctx, ask: AskUser, *, signal):
+ original_args = _args_to_dict(ctx.args)
+ try:
+ answer = await self._channel.approve(
+ tool_name=ctx.tool_call.name,
+ tool_call_id=ctx.tool_call.id,
+ args=original_args,
+ details=ask.details,
+ timeout=ask.timeout_seconds,
+ signal=signal,
+ )
+ except HitlTimedOut:
+ return BeforeToolCallResult(
+ block=True,
+ deny_reason="approval_timeout",
+ reason="approval_timeout",
+ hitl_trace={"decision": "timed_out"},
+ )
+ except HitlCancelled as exc:
+ return BeforeToolCallResult(
+ block=True,
+ deny_reason=f"cancelled: {exc.reason}",
+ reason=f"cancelled: {exc.reason}",
+ hitl_trace={"decision": "cancelled", "reason": exc.reason},
+ )
+
+ if answer.decision == "approve":
+ return None
+ if answer.decision == "deny":
+ return BeforeToolCallResult(
+ block=True,
+ deny_reason=answer.reason,
+ reason=answer.reason,
+ hitl_trace={"decision": "human_deny", "reason": answer.reason},
+ )
+ if answer.decision == "edit":
+ return BeforeToolCallResult(
+ edited_args=answer.edited_args,
+ hitl_trace={
+ "decision": "edit",
+ "original_args": original_args,
+ "edited_args": answer.edited_args,
+ },
+ )
+
+
+class ConfirmToolCallMiddleware(ApprovalPolicyMiddleware):
+ """Convenience wrapper: 'always ask the human for these tool names'."""
+
+ def __init__(
+ self,
+ channel: HitlChannel,
+ *,
+ require_confirm: Union[
+ Callable[[BeforeToolCallContext], bool], Iterable[str], None
+ ] = None,
+ details_fn: Callable[[BeforeToolCallContext], dict] | None = None,
+ timeout_seconds: float | None = None,
+ ):
+ if require_confirm is None:
+
+ def matcher(ctx):
+ return True
+
+ elif callable(require_confirm):
+ matcher = require_confirm
+ else:
+ names = set(require_confirm)
+
+ def matcher(ctx):
+ return ctx.tool_call.name in names
+
+ def policy(ctx) -> ApprovalDecision:
+ if matcher(ctx):
+ return AskUser(
+ timeout_seconds=timeout_seconds,
+ details=details_fn(ctx) if details_fn else None,
+ )
+ return Approve()
+
+ super().__init__(channel, policy=policy)
diff --git a/tests/hitl/test_approval_policy_middleware.py b/tests/hitl/test_approval_policy_middleware.py
new file mode 100644
index 0000000..2ee1fec
--- /dev/null
+++ b/tests/hitl/test_approval_policy_middleware.py
@@ -0,0 +1,127 @@
+import asyncio
+
+from cubepi.agent.types import AgentContext, BeforeToolCallContext
+from cubepi.hitl import Approve, ApproveAnswer, AskUser, Deny
+from cubepi.hitl.channel import InMemoryChannel
+from cubepi.hitl.middleware import ApprovalPolicyMiddleware
+from cubepi.providers.base import AssistantMessage, TextContent, ToolCall
+
+
+def _ctx(tool_call_id="tc-1") -> BeforeToolCallContext:
+ return BeforeToolCallContext(
+ assistant_message=AssistantMessage(
+ content=[
+ TextContent(text=""),
+ ToolCall(id=tool_call_id, name="bash", arguments={"cmd": "ls"}),
+ ],
+ stop_reason="tool_use",
+ ),
+ tool_call=ToolCall(id=tool_call_id, name="bash", arguments={"cmd": "ls"}),
+ args={"cmd": "ls"},
+ context=AgentContext(system_prompt="", messages=[], tools=[]),
+ )
+
+
+async def test_approve_policy_passthrough():
+ mw = ApprovalPolicyMiddleware(InMemoryChannel(), policy=lambda c: Approve())
+ result = await mw.before_tool_call(_ctx())
+ assert result is None
+
+
+async def test_deny_policy_blocks_without_channel():
+ ch = InMemoryChannel()
+ mw = ApprovalPolicyMiddleware(ch, policy=lambda c: Deny(reason="forbidden"))
+ result = await mw.before_tool_call(_ctx())
+ assert result.block is True
+ assert result.deny_reason == "forbidden"
+ assert result.hitl_trace["decision"] == "policy_deny"
+ assert ch.pending is None # channel never invoked
+
+
+async def test_ask_user_policy_invokes_channel_human_approve():
+ ch = InMemoryChannel()
+
+ async def host():
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ await ch.answer(ch.pending.question_id, ApproveAnswer(decision="approve"))
+
+ asyncio.create_task(host())
+ mw = ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser())
+ result = await mw.before_tool_call(_ctx())
+ assert result is None
+
+
+async def test_ask_user_policy_human_deny_blocks():
+ ch = InMemoryChannel()
+
+ async def host():
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ await ch.answer(
+ ch.pending.question_id, ApproveAnswer(decision="deny", reason="no")
+ )
+
+ asyncio.create_task(host())
+ mw = ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser())
+ result = await mw.before_tool_call(_ctx())
+ assert result.block is True
+ assert result.hitl_trace["decision"] == "human_deny"
+ assert result.deny_reason == "no"
+
+
+async def test_ask_user_policy_human_edit_passes_edited_args():
+ ch = InMemoryChannel()
+
+ async def host():
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ await ch.answer(
+ ch.pending.question_id,
+ ApproveAnswer(decision="edit", edited_args={"cmd": "ls -l"}),
+ )
+
+ asyncio.create_task(host())
+ mw = ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser())
+ result = await mw.before_tool_call(_ctx())
+ assert result.edited_args == {"cmd": "ls -l"}
+ assert result.hitl_trace["decision"] == "edit"
+ assert result.hitl_trace["original_args"] == {"cmd": "ls"}
+
+
+async def test_timeout_translates_to_approval_timeout_deny():
+ ch = InMemoryChannel()
+ mw = ApprovalPolicyMiddleware(
+ ch,
+ policy=lambda c: AskUser(timeout_seconds=0.05),
+ )
+ result = await mw.before_tool_call(_ctx())
+ assert result.block is True
+ assert result.deny_reason == "approval_timeout"
+ assert result.hitl_trace["decision"] == "timed_out"
+
+
+async def test_cancel_translates_to_cancelled_deny():
+ ch = InMemoryChannel()
+
+ async def canceller():
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ await ch.cancel(ch.pending.question_id, reason="closed tab")
+
+ asyncio.create_task(canceller())
+ mw = ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser())
+ result = await mw.before_tool_call(_ctx())
+ assert result.block is True
+ assert "cancelled: closed tab" == result.deny_reason
+ assert result.hitl_trace["decision"] == "cancelled"
+
+
+async def test_async_policy_is_awaited():
+ ch = InMemoryChannel()
+
+ async def policy(c):
+ return Approve()
+
+ mw = ApprovalPolicyMiddleware(ch, policy=policy)
+ assert (await mw.before_tool_call(_ctx())) is None
diff --git a/tests/hitl/test_ask_user_tool.py b/tests/hitl/test_ask_user_tool.py
new file mode 100644
index 0000000..1bb1d3e
--- /dev/null
+++ b/tests/hitl/test_ask_user_tool.py
@@ -0,0 +1,95 @@
+import asyncio
+
+from cubepi.hitl.ask_user import ask_user_tool
+from cubepi.hitl.channel import InMemoryChannel
+
+
+async def test_ask_user_tool_is_sequential():
+ tool = ask_user_tool(InMemoryChannel())
+ assert tool.name == "ask_user"
+ assert tool.execution_mode == "sequential"
+
+
+async def test_ask_user_tool_returns_answers_in_details():
+ ch = InMemoryChannel()
+
+ async def host():
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ await ch.answer(ch.pending.question_id, {"color": "red"})
+
+ tool = ask_user_tool(ch)
+ asyncio.create_task(host())
+ result = await tool.execute(
+ "tc-1",
+ tool.parameters.model_validate(
+ {
+ "questions": [{"key": "color", "prompt": "Pick:"}],
+ }
+ ),
+ signal=None,
+ on_update=lambda p: None,
+ )
+ assert result.details["hitl"]["answers"] == {"color": "red"}
+ # Content has a human-readable summary too
+ assert "color" in result.content[0].text
+
+
+async def test_ask_user_tool_cancel_becomes_tool_error():
+ ch = InMemoryChannel()
+
+ async def canceller():
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ await ch.cancel(ch.pending.question_id, reason="closed tab")
+
+ tool = ask_user_tool(ch)
+ asyncio.create_task(canceller())
+ result = await tool.execute(
+ "tc-1",
+ tool.parameters.model_validate({"questions": [{"key": "x", "prompt": "?"}]}),
+ signal=None,
+ on_update=lambda p: None,
+ )
+ assert result.is_error is True
+ assert result.details["hitl"]["outcome"] == "cancelled"
+ assert result.details["hitl"]["reason"] == "closed tab"
+
+
+async def test_ask_user_tool_timeout_becomes_tool_error():
+ ch = InMemoryChannel(default_timeout=0.05)
+ tool = ask_user_tool(ch)
+ result = await tool.execute(
+ "tc-1",
+ tool.parameters.model_validate({"questions": [{"key": "x", "prompt": "?"}]}),
+ signal=None,
+ on_update=lambda p: None,
+ )
+ assert result.is_error is True
+ assert result.details["hitl"]["outcome"] == "timed_out"
+
+
+async def test_ask_user_tool_multi_question_form():
+ ch = InMemoryChannel()
+
+ async def host():
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ await ch.answer(ch.pending.question_id, {"color": "red", "size": ["s", "l"]})
+
+ tool = ask_user_tool(ch)
+ asyncio.create_task(host())
+ result = await tool.execute(
+ "tc-1",
+ tool.parameters.model_validate(
+ {
+ "questions": [
+ {"key": "color", "prompt": "Color?"},
+ {"key": "size", "prompt": "Sizes?", "multi_select": True},
+ ],
+ }
+ ),
+ signal=None,
+ on_update=lambda p: None,
+ )
+ assert result.details["hitl"]["answers"]["size"] == ["s", "l"]
diff --git a/tests/hitl/test_confirm_tool_call_middleware.py b/tests/hitl/test_confirm_tool_call_middleware.py
new file mode 100644
index 0000000..85e206f
--- /dev/null
+++ b/tests/hitl/test_confirm_tool_call_middleware.py
@@ -0,0 +1,67 @@
+import asyncio
+
+from cubepi.agent.types import AgentContext, BeforeToolCallContext
+from cubepi.hitl import ApproveAnswer
+from cubepi.hitl.channel import InMemoryChannel
+from cubepi.hitl.middleware import ConfirmToolCallMiddleware
+from cubepi.providers.base import AssistantMessage, TextContent, ToolCall
+
+
+def _ctx(name="bash"):
+ return BeforeToolCallContext(
+ assistant_message=AssistantMessage(
+ content=[TextContent(text=""), ToolCall(id="tc", name=name, arguments={})],
+ stop_reason="tool_use",
+ ),
+ tool_call=ToolCall(id="tc", name=name, arguments={}),
+ args={},
+ context=AgentContext(system_prompt="", messages=[], tools=[]),
+ )
+
+
+async def test_set_based_require_confirm_only_asks_for_listed():
+ ch = InMemoryChannel()
+
+ async def host():
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ await ch.answer(ch.pending.question_id, ApproveAnswer(decision="approve"))
+
+ asyncio.create_task(host())
+ mw = ConfirmToolCallMiddleware(ch, require_confirm={"bash"})
+ # bash: prompts
+ assert (await mw.before_tool_call(_ctx("bash"))) is None
+ # read_file: not in set — passes through silently
+ assert (await mw.before_tool_call(_ctx("read_file"))) is None
+ # bash prompted exactly once; read_file did not engage channel
+ assert ch.pending is None
+
+
+async def test_predicate_require_confirm():
+ ch = InMemoryChannel()
+
+ async def host():
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ await ch.answer(ch.pending.question_id, ApproveAnswer(decision="approve"))
+
+ asyncio.create_task(host())
+
+ def needs_confirm(ctx):
+ return ctx.tool_call.name.startswith("dangerous_")
+
+ mw = ConfirmToolCallMiddleware(ch, require_confirm=needs_confirm)
+ assert (await mw.before_tool_call(_ctx("dangerous_op"))) is None
+
+
+async def test_default_none_asks_for_every_tool():
+ ch = InMemoryChannel()
+
+ async def host():
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ await ch.answer(ch.pending.question_id, ApproveAnswer(decision="approve"))
+
+ asyncio.create_task(host())
+ mw = ConfirmToolCallMiddleware(ch) # no require_confirm
+ assert (await mw.before_tool_call(_ctx("anything"))) is None