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
docs(hitl): cross-reference HITL across 7 existing doc pages
xf gong007970521314
diff --git a/website/docs/getting-started/core-concepts.md b/website/docs/getting-started/core-concepts.mdindex c4811a6..0112a2e 100644--- a/website/docs/getting-started/core-concepts.md+++ b/website/docs/getting-started/core-concepts.md@@ -99,12 +99,12 @@ Streams and events are two layers:- **Provider streams** — `MessageStream` yields *provider* events:`start`, `text_start`, `text_delta`, `text_end`, `thinking_*`,`toolcall_*`, `done`, `error`. This is the raw token stream.-- **Agent events** — what `agent.subscribe(...)` receives. Eleven- types covering the entire loop: `agent_start`, `agent_end`,+- **Agent events** — what `agent.subscribe(...)` receives. 15+ types covering the entire loop + HITL: `agent_start`, `agent_end`,`turn_start`, `turn_end`, `message_start`, `message_update`,`message_end`, `tool_execution_start`, `tool_execution_update`,- `tool_execution_end`. `message_update` wraps the provider event- inside `event.stream_event`.+ `tool_execution_end`, `hitl_request`, `hitl_answer`,+ `agent_suspended`, `agent_aborted`.Subscribe to agent events for UI; for low-level token routing dig into`event.stream_event`. See [Streaming Events](../guides/agents/streaming).@@ -140,8 +140,51 @@ class Checkpointer(Protocol):Bind one to an agent with `Agent(checkpointer=cp, thread_id="…")` andthe loop will append each new message as it lands, restoring historyon the first `prompt()`. Built-in backends: `MemoryCheckpointer`,-`SQLiteCheckpointer`, `PostgresCheckpointer`. See-[Checkpointing → SQLite](../guides/checkpointing/sqlite).+`SQLiteCheckpointer`, `PostgresCheckpointer`, `MySQLCheckpointer`.++HITL adds two optional methods for cross-process suspend/resume:+`save_pending_request` / `load_pending_request`. All first-party+backends implement them. See [HITL guide](../guides/hitl).++## HITL (Human-in-the-Loop)++cubepi ships a built-in `cubepi.hitl` module for scenarios where the+agent needs to **pause and wait for a human**:++- **Sandbox confirmation** — a dangerous tool (bash, file write) needs+ approve / deny / edit before running.+- **Mid-run questions** — the agent surfaces a structured form to the user+ and waits for the answer.++```python+from cubepi.hitl import InMemoryChannel, ConfirmToolCallMiddleware, ask_user_tool++channel = InMemoryChannel()++agent = Agent(+ provider=…, model=…,+ tools=[bash_tool, ask_user_tool(channel)],+ middleware=[ConfirmToolCallMiddleware(channel, require_confirm={"bash"})],+ channel=channel,+)+```++The channel is an `await`-able coroutine collaborator: tool and+middleware authors write `await channel.ask(...)` or+`await channel.confirm(...)` and the channel handles the suspend. Host+code (your web app / TUI) subscribes to `channel.subscribe()` or polls+`channel.pending`, renders the request to the user, and posts the+answer via `channel.answer(qid, answer)`.++Two channel backends ship in-box:+- **`InMemoryChannel`** — single process (CLI, notebook, tests).+- **`CheckpointedChannel`** — cross-process (web service). The pending+ request is persisted to the checkpointer; a different process can+ answer hours later via `Agent.respond(question_id=, answer=)`.++Full details — the three HITL verbs, both built-in middlewares, the+cross-process suspend/resume protocol, events, trace spans, and error+reference — are in the [HITL guide](../guides/hitl).## Tracer (optional)diff --git a/website/docs/guides/agents/tool-use.md b/website/docs/guides/agents/tool-use.mdindex ed722bc..b3b39b8 100644--- a/website/docs/guides/agents/tool-use.md+++ b/website/docs/guides/agents/tool-use.md@@ -81,6 +81,10 @@ There are two ways to opt out of parallel mode:)```+The built-in `ask_user` HITL tool (see [HITL guide](../hitl)) uses+`execution_mode="sequential"` — it pauses the agent for human input and+cannot share a turn with other tools.+Use sequential mode when tools mutate shared state (a DB, a counter)and you want a deterministic order.diff --git a/website/docs/guides/checkpointing/postgres.md b/website/docs/guides/checkpointing/postgres.mdindex 1e07e35..058ff71 100644--- a/website/docs/guides/checkpointing/postgres.md+++ b/website/docs/guides/checkpointing/postgres.md@@ -177,6 +177,17 @@ to so the schema is forward-compatible.migrations didn't run. Apply the host alembic upgrade first.- **`CubepiSchemaMismatch`** — You upgraded cubepi but didn't generatea new migration. Generate one, apply it, and CubePi will start.++ :::info Schema v2 (HITL)++ cubepi ≥ the HITL feature bumps `EXPECTED_SCHEMA_VERSION` from 1 to 2+ and adds a `pending_request JSONB NULL` column to `cubepi_threads`.+ Your host alembic upgrade must call+ `add_pending_request_column_op()` (from+ `cubepi.checkpointer.postgres.alembic_helpers`) before bumping the+ schema_version row. See the [HITL guide](../hitl) for the full+ cross-process flow.+ :::- **Connection pool exhaustion under load** — Default `max_pool_size=10`.Bump it if your app's concurrent agent count is higher than that.- **`asyncpg.exceptions.UndefinedTableError` outside `__aenter__`** —diff --git a/website/docs/guides/checkpointing/sqlite.md b/website/docs/guides/checkpointing/sqlite.mdindex f6af8d5..f872f09 100644--- a/website/docs/guides/checkpointing/sqlite.md+++ b/website/docs/guides/checkpointing/sqlite.md@@ -82,6 +82,22 @@ CREATE TABLE thread_extra (This schema is append-only. CubePi never updates or deletes rows.+## HITL pending table++When the [HITL](../hitl) module is in use, an additional table is+created automatically on `__aenter__`:++```sql+CREATE TABLE IF NOT EXISTS thread_pending_request (+ thread_id TEXT PRIMARY KEY,+ request_json TEXT NOT NULL,+ created_at REAL NOT NULL DEFAULT (julianday('now'))+);+```++No manual migration is needed — `CREATE TABLE IF NOT EXISTS` is+idempotent.+## When CubePi readsOn the **first** `prompt()` after instantiation, CubePi callsdiff --git a/website/docs/guides/middleware/composition.md b/website/docs/guides/middleware/composition.mdindex c40adb6..60341d7 100644--- a/website/docs/guides/middleware/composition.md+++ b/website/docs/guides/middleware/composition.md@@ -17,7 +17,7 @@ to remember "before" or "after" precedence guesses.| `transform_context` | **Chain** — each sees previous output | Yes || `convert_to_llm` | **Last wins** | Only the last one runs || `transform_system_prompt` | **Chain** | Yes |-| `before_tool_call` | **First block stops** | First in list wins blocks |+| `before_tool_call` | **First block stops**; non-block accumulates | Block wins; `edited_args` last-writer-wins; `hitl_trace` merges || `after_tool_call` | **Later overrides earlier** | Last write wins || `should_stop_after_turn` | **Any `True` stops** (OR) | No || `after_model_response` | **Chain with merge semantics** | See below |@@ -53,22 +53,29 @@ both).## `before_tool_call`-First `block=True` short-circuits the rest. Use to chain policy-layers from most-restrictive to least:+First `block=True` short-circuits the rest. **Non-block returns+accumulate:** `edited_args` propagates downstream (each middleware sees+the edited form from the one above), and `hitl_trace` merges across the+chain (with older keys archived under `_chain` when overwritten).++Use to chain policy layers from most-restrictive to least:```pythonagent = Agent(middleware=[RateLimiter(), # blocks on rate quota- SafetyFilter(), # blocks on dangerous args- AuditLogger(), # never blocks; just records+ SafetyFilter(), # blocks on dangerous args; may edit+ AuditLogger(), # never blocks; records for observability],)```If `RateLimiter` returns `block=True`, `SafetyFilter` and-`AuditLogger`'s `before_tool_call` don't run. `AuditLogger.after_tool_call`-still fires because that's a different hook.+`AuditLogger`'s `before_tool_call` don't run. If `SafetyFilter` returns+`edited_args={"cmd": "rm /tmp/foo"}`, the *tool* runs with the edited+args and `AuditLogger` sees the edit in `hitl_trace["_chain"]`.+`AuditLogger.after_tool_call` still fires because that's a different+hook.## `after_tool_call`diff --git a/website/docs/guides/middleware/examples.md b/website/docs/guides/middleware/examples.mdindex dbdf15f..cbf5184 100644--- a/website/docs/guides/middleware/examples.md+++ b/website/docs/guides/middleware/examples.md@@ -236,6 +236,57 @@ class JSONOutputValidator(Middleware):The agent will skip tool execution and immediately re-prompt themodel with the feedback message in context.+## Human-in-the-loop tool confirmation++cubepi ships two built-in HITL middlewares in `cubepi.hitl`:++**`ConfirmToolCallMiddleware`** — "always ask the human for this tool":++```python+from cubepi.hitl import ConfirmToolCallMiddleware, InMemoryChannel++channel = InMemoryChannel()+agent = Agent(+ provider=…, model=…,+ middleware=[+ ConfirmToolCallMiddleware(+ channel,+ require_confirm={"bash", "write_file"},+ ),+ ],+)+```++The agent pauses on every `bash` or `write_file` call and waits for the+host to `channel.answer(qid, ApproveAnswer(decision="approve"))`. The+result drives the tool: `approve` runs it, `deny` blocks with a reason,+`edit` re-validates and runs the edited args.++**`ApprovalPolicyMiddleware`** — for hosts that classify tool calls via+a policy engine:++```python+from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny++def my_policy(ctx):+ if ctx.tool_call.name in ("read_file", "grep"):+ return Approve()+ if ctx.tool_call.name.startswith("dangerous_"):+ return Deny(reason="blocked")+ return AskUser(timeout_seconds=180)++agent = Agent(+ provider=…, model=…,+ middleware=[ApprovalPolicyMiddleware(channel, policy=my_policy)],+)+```++`Deny` skips the channel entirely (hard block). `AskUser` triggers the+channel's approve flow. `Approve` returns immediately.++Full details — timeout semantics, edit semantics, events, trace spans,+cross-process suspend/resume — are in the [HITL guide](../hitl).+## See also- [The 7 Hooks](./hooks) — exact semantics of each hook.diff --git a/website/docs/guides/middleware/hooks.md b/website/docs/guides/middleware/hooks.mdindex 36f2019..09647ba 100644--- a/website/docs/guides/middleware/hooks.md+++ b/website/docs/guides/middleware/hooks.md@@ -89,7 +89,8 @@ Return `BeforeToolCallResult(block=True, reason="…")` to short-circuit— CubePi feeds the reason back as the tool result with`is_error=True`. Return `None` (or no return) to proceed.-Use for: permissions, rate limiting, dry-run modes, sandboxing.+Use for: permissions, rate limiting, dry-run modes, sandboxing,+human-in-the-loop confirmation (see [HITL guide](../hitl)).Composition: **first `block=True` short-circuits** the chain.