CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat(hitl): types, exception hierarchy, policy enum, test helpers
xf gong09fa2622648e
diff --git a/cubepi/hitl/__init__.py b/cubepi/hitl/__init__.pynew file mode 100644index 0000000..bebaf2f--- /dev/null+++ b/cubepi/hitl/__init__.py@@ -0,0 +1,65 @@+"""Human-in-the-Loop (HITL) primitives for cubepi agents.++See dev/specs/2026-05-28-hitl-channel.md for the full design.+"""++from cubepi.hitl.exceptions import (+ HitlAborted,+ HitlCancelled,+ HitlConcurrencyError,+ HitlControlException,+ HitlDetached,+ HitlDurabilityNotGuaranteed,+ HitlError,+ HitlInconsistentState,+ HitlMissingAnswer,+ HitlNoPendingRequest,+ HitlStaleAnswer,+ HitlTimedOut,+)+from cubepi.hitl.policy import (+ Approve,+ ApprovalDecision,+ AskUser,+ Deny,+)+from cubepi.hitl.types import (+ ApproveAnswer,+ ApproveRequest,+ AskRequest,+ ConfirmRequest,+ HitlPayload,+ HitlRequest,+ Option,+ Question,+)++__all__ = [+ # types+ "ApproveAnswer",+ "ApproveRequest",+ "AskRequest",+ "ConfirmRequest",+ "HitlPayload",+ "HitlRequest",+ "Option",+ "Question",+ # policy+ "Approve",+ "ApprovalDecision",+ "AskUser",+ "Deny",+ # exceptions+ "HitlAborted",+ "HitlCancelled",+ "HitlConcurrencyError",+ "HitlControlException",+ "HitlDetached",+ "HitlDurabilityNotGuaranteed",+ "HitlError",+ "HitlInconsistentState",+ "HitlMissingAnswer",+ "HitlNoPendingRequest",+ "HitlStaleAnswer",+ "HitlTimedOut",+]diff --git a/cubepi/hitl/exceptions.py b/cubepi/hitl/exceptions.pynew file mode 100644index 0000000..d815f88--- /dev/null+++ b/cubepi/hitl/exceptions.py@@ -0,0 +1,58 @@+from __future__ import annotations+++class HitlControlException(BaseException):+ """Base for HITL control-flow exceptions.++ Inherits BaseException so existing `except Exception:` handlers in+ cubepi.agent.tools._prepare_tool_call and _execute_prepared do NOT+ swallow these — mirrors asyncio.CancelledError.+ """+++class HitlCancelled(HitlControlException):+ def __init__(self, reason: str):+ super().__init__(reason)+ self.reason = reason+++class HitlTimedOut(HitlControlException):+ def __init__(self, seconds: float):+ super().__init__(f"HITL request timed out after {seconds} seconds")+ self.seconds = seconds+++class HitlDetached(HitlControlException):+ pass+++class HitlAborted(HitlControlException):+ pass+++class HitlError(Exception):+ """Base for caller-fixable HITL errors (misuse, not control flow)."""+++class HitlConcurrencyError(HitlError):+ pass+++class HitlStaleAnswer(HitlError):+ pass+++class HitlNoPendingRequest(HitlError):+ pass+++class HitlMissingAnswer(HitlError):+ pass+++class HitlInconsistentState(HitlError):+ pass+++class HitlDurabilityNotGuaranteed(HitlError):+ passdiff --git a/cubepi/hitl/policy.py b/cubepi/hitl/policy.pynew file mode 100644index 0000000..7009eec--- /dev/null+++ b/cubepi/hitl/policy.py@@ -0,0 +1,24 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Union+++@dataclass(frozen=True)+class Approve:+ pass+++@dataclass(frozen=True)+class Deny:+ reason: str+++@dataclass(frozen=True)+class AskUser:+ prompt: str | None = None+ timeout_seconds: float | None = None+ details: dict | None = None+++ApprovalDecision = Union[Approve, Deny, AskUser]diff --git a/cubepi/hitl/types.py b/cubepi/hitl/types.pynew file mode 100644index 0000000..d0a2400--- /dev/null+++ b/cubepi/hitl/types.py@@ -0,0 +1,56 @@+from __future__ import annotations++from typing import Any, Literal, Union++from pydantic import BaseModel, Field+++class Option(BaseModel):+ label: str+ value: str+ description: str | None = None+ allow_input: bool = False+++class Question(BaseModel):+ key: str+ prompt: str+ options: list[Option] | None = None+ multi_select: bool = False+ required: bool = True+++class ConfirmRequest(BaseModel):+ kind: Literal["confirm"] = "confirm"+ prompt: str+ details: dict[str, Any] | None = None+++class ApproveRequest(BaseModel):+ kind: Literal["approve"] = "approve"+ tool_name: str+ tool_call_id: str+ args: dict[str, Any]+ details: dict[str, Any] | None = None+++class AskRequest(BaseModel):+ kind: Literal["ask"] = "ask"+ questions: list[Question]+++HitlPayload = Union[ConfirmRequest, ApproveRequest, AskRequest]+++class HitlRequest(BaseModel):+ question_id: str+ thread_id: str | None+ payload: HitlPayload = Field(discriminator="kind")+ created_at: float+ timeout_seconds: float | None = None+++class ApproveAnswer(BaseModel):+ decision: Literal["approve", "deny", "edit"]+ edited_args: dict[str, Any] | None = None+ reason: str | None = Nonediff --git a/tests/hitl/__init__.py b/tests/hitl/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tests/hitl/conftest.py b/tests/hitl/conftest.pynew file mode 100644index 0000000..f4ca9af--- /dev/null+++ b/tests/hitl/conftest.py@@ -0,0 +1,22 @@+# tests/hitl/conftest.py+import asyncio+++async def await_pending(channel, *, timeout: float = 2.0) -> None:+ """Wait until channel.pending becomes non-None, or fail the test on timeout.++ Use this in tests that race a host coroutine against an awaiting agent.+ Replaces the `while ch.pending is None: await asyncio.sleep(0)` pattern,+ which silently hangs if the host task crashes.+ """++ async def _wait():+ while channel.pending is None:+ await asyncio.sleep(0)++ try:+ await asyncio.wait_for(_wait(), timeout=timeout)+ except asyncio.TimeoutError as exc:+ raise AssertionError(+ f"channel.pending did not become set within {timeout}s"+ ) from excdiff --git a/tests/hitl/test_exceptions.py b/tests/hitl/test_exceptions.pynew file mode 100644index 0000000..745e3c7--- /dev/null+++ b/tests/hitl/test_exceptions.py@@ -0,0 +1,69 @@+import pytest+from cubepi.hitl.exceptions import (+ HitlControlException,+ HitlCancelled,+ HitlTimedOut,+ HitlDetached,+ HitlAborted,+ HitlError,+ HitlConcurrencyError,+ HitlStaleAnswer,+ HitlNoPendingRequest,+ HitlMissingAnswer,+ HitlInconsistentState,+ HitlDurabilityNotGuaranteed,+)+++def test_control_exceptions_are_baseexception_not_exception():+ for cls in (+ HitlControlException,+ HitlCancelled,+ HitlTimedOut,+ HitlDetached,+ HitlAborted,+ ):+ assert issubclass(cls, BaseException)+ assert not issubclass(cls, Exception)+++def test_control_exception_subclassing():+ assert issubclass(HitlCancelled, HitlControlException)+ assert issubclass(HitlTimedOut, HitlControlException)+ assert issubclass(HitlDetached, HitlControlException)+ assert issubclass(HitlAborted, HitlControlException)+++def test_regular_errors_are_exception():+ for cls in (+ HitlError,+ HitlConcurrencyError,+ HitlStaleAnswer,+ HitlNoPendingRequest,+ HitlMissingAnswer,+ HitlInconsistentState,+ HitlDurabilityNotGuaranteed,+ ):+ assert issubclass(cls, Exception)+++def test_hitl_cancelled_carries_reason():+ exc = HitlCancelled("user clicked cancel")+ assert exc.reason == "user clicked cancel"+ assert "user clicked cancel" in str(exc)+++def test_hitl_timed_out_carries_seconds():+ exc = HitlTimedOut(30.0)+ assert exc.seconds == 30.0+ assert "30" in str(exc)+++def test_except_exception_does_not_catch_control():+ try:+ try:+ raise HitlCancelled("x")+ except Exception:+ pytest.fail("HitlCancelled should not be caught by except Exception")+ except HitlControlException as exc:+ assert exc.reason == "x"diff --git a/tests/hitl/test_types.py b/tests/hitl/test_types.pynew file mode 100644index 0000000..8af806e--- /dev/null+++ b/tests/hitl/test_types.py@@ -0,0 +1,82 @@+import pytest+from cubepi.hitl.types import (+ Option,+ Question,+ ConfirmRequest,+ ApproveRequest,+ AskRequest,+ HitlRequest,+ ApproveAnswer,+)+++def test_option_default_allow_input_false():+ o = Option(label="A", value="a")+ assert o.allow_input is False+ assert o.description is None+++def test_question_defaults():+ q = Question(key="color", prompt="Pick:")+ assert q.options is None+ assert q.multi_select is False+ assert q.required is True+++def test_confirm_request_kind_literal():+ r = ConfirmRequest(prompt="ok?")+ assert r.kind == "confirm"+++def test_approve_request_kind_literal():+ r = ApproveRequest(tool_name="bash", tool_call_id="tc-1", args={"cmd": "ls"})+ assert r.kind == "approve"+++def test_ask_request_kind_literal():+ r = AskRequest(questions=[Question(key="x", prompt="?")])+ assert r.kind == "ask"+++def test_hitl_request_envelope_round_trip():+ req = HitlRequest(+ question_id="tc-1",+ thread_id="t-7",+ payload=ApproveRequest(tool_name="bash", tool_call_id="tc-1", args={}),+ created_at=1.0,+ timeout_seconds=42.0,+ )+ raw = req.model_dump_json()+ back = HitlRequest.model_validate_json(raw)+ assert back == req+ assert back.payload.kind == "approve"+++def test_hitl_request_discriminated_union_round_trip_for_each_kind():+ payloads = [+ ConfirmRequest(prompt="ok?"),+ ApproveRequest(tool_name="t", tool_call_id="c", args={"a": 1}),+ AskRequest(questions=[Question(key="k", prompt="p")]),+ ]+ for p in payloads:+ req = HitlRequest(question_id="q", thread_id=None, payload=p, created_at=0.0)+ back = HitlRequest.model_validate_json(req.model_dump_json())+ assert type(back.payload) is type(p)+++def test_approve_answer_decisions():+ assert ApproveAnswer(decision="approve").decision == "approve"+ assert ApproveAnswer(decision="deny", reason="no").reason == "no"+ assert ApproveAnswer(decision="edit", edited_args={"x": 1}).edited_args == {"x": 1}+++def test_approval_decision_dataclasses_frozen():+ from cubepi.hitl.policy import Approve, Deny, AskUser++ a = Approve()+ d = Deny(reason="forbidden")+ u = AskUser(timeout_seconds=10.0)+ assert d.reason == "forbidden"+ assert u.timeout_seconds == 10.0+ with pytest.raises(Exception):+ a.foo = "bar" # frozen dataclass