Skip to content

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

docs(hitl): split the HITL guide into 4 sub-pages

xf gong19f2bbdcc792
diff --git a/website/docs/guides/hitl.md b/website/docs/guides/hitl.md
deleted file mode 100644
index 1730bdc..0000000
--- a/website/docs/guides/hitl.md
+++ /dev/null
@@ -1,519 +0,0 @@
----
-title: Human-in-the-Loop (HITL)
-description: "Add human-in-the-loop pauses to your CubePi agent with confirm, approve, and structured ask verbs."
-sidebar_position: 10
----
-
-# Human-in-the-Loop (HITL)
-
-CubePi's HITL channel lets an agent **pause and ask a human** before proceeding.
-It handles two recurring patterns with a single primitive:
-
-1. **Sandbox tool confirmation** — a dangerous tool (bash, file writes, API
- mutations) needs approve / deny / edit from a human before running.
-2. **Mid-run structured questions** — the agent needs a specific selection or
- form answer from the user before it can continue.
-
-The channel is an `await`-able coroutine collaborator. Tool authors write
-`await channel.ask(...)` and the channel handles the pause. Host code
-(subscribers) renders the pending request and posts an answer. Two backends
-cover the full spectrum:
-
-- `InMemoryChannel` — CLI, notebooks, tests. Process dies, pending is lost.
-- `CheckpointedChannel` — web services. Persists the pending request to a
- `Checkpointer` so a different process (or the same process after restart)
- can pick up and answer hours later.
-
-## Architecture
-
-```text
-┌────────────────────────────────────────────────────────┐
-│ Host (cubebox web service / CLI / TUI) │
-│ │
-│ subscribe to channel.pending ◄──── answer / cancel │
-└──────────────────────┬─────────────────────────────────┘
- │
- ┌─────────────▼──────────────┐
- │ HitlChannel (Protocol) │
- │ confirm / approve / ask │
- │ pending / answer / cancel │
- └──────┬──────────────┬──────┘
- │ │
- ┌──────────▼───┐ ┌──────▼────────────┐
- │InMemoryChannel│ │CheckpointedChannel│
- │ (Future+Queue)│ │ (Future + persi- │
- │ │ │ sts to Checkpo- │
- │ │ │ inter) │
- └───────────────┘ └───────────────────┘
- │ │
- │ used by ────┤
- │ │
- ┌──────────▼──────────────▼────────────┐
- │ ask_user tool ConfirmToolCallMW │
- │ (structured form) (approve/deny/ │
- │ edit per-tool) │
- └──────────────────────────────────────┘
- │
- ┌─────────────▼──────────────┐
- │ cubepi Agent loop │
- │ (BeforeToolCallResult │
- │ carries hitl_trace) │
- └────────────────────────────┘
-```
-
-## Channel types
-
-### `InMemoryChannel`
-
-For single-process use. Holds an `asyncio.Future` internally — the host
-calls `channel.answer()` from the same event loop.
-
-```python
-from cubepi.hitl import InMemoryChannel
-
-channel = InMemoryChannel(
- default_timeout=180.0, # per-call timeout; None = no timeout (default)
-)
-```
-
-### `CheckpointedChannel`
-
-For cross-process use. On every `confirm / approve / ask`, the `HitlRequest`
-is persisted via `Checkpointer.save_pending_request(thread_id, ...)`. On
-`channel.answer()`, the pending is cleared. On `HitlDetached` (graceful
-suspend), the pending stays so a later `Agent.respond()` can resume.
-
-```python
-from cubepi.hitl import CheckpointedChannel
-from cubepi.checkpointer.sqlite import SQLiteCheckpointer # or postgres / mysql
-
-async with SQLiteCheckpointer("path/to.db") as cp:
- channel = CheckpointedChannel(
- checkpointer=cp,
- thread_id="conversation-42",
- default_timeout=None, # cross-process: typical to disable
- allow_inside_custom_tool=False, # safety gate (see Durable scope below)
- )
-```
-
-`CheckpointedChannel.__init__` validates the checkpointer implements
-`save_pending_request` and `load_pending_request` — it fails early with
-`HitlError` if not.
-
-## The three verbs
-
-### `confirm(prompt, *, details, timeout, signal) → bool`
-
-A simple yes/no question. The host answers `True` or `False`.
-
-```python
-if await channel.confirm("Deploy to production?", details={"env": "prod"}):
- await deploy()
-```
-
-### `approve(tool_name, tool_call_id, args, *, details, timeout, signal) → ApproveAnswer`
-
-The sandbox-confirm verb. Returns an `ApproveAnswer` with one of three decisions:
-
-| Decision | Result |
-|---|---|
-| `"approve"` | Tool runs with the original args. |
-| `"deny"` | Tool is blocked; `tool_result.is_error=True` with `details["hitl"]["decision"]="human_deny"`. |
-| `"edit"` | Tool runs with the edited args (re-validated against the tool's pydantic parameter model). |
-
-For `approve` requests, the envelope's `question_id` is set to the LLM's
-`tool_call_id` — no separate UUID, so host code can correlate by the same
-ID it already tracks from the tool stream.
-
-### `ask(questions, *, timeout, signal) → dict[str, str | list[str]]`
-
-A structured form with one or more `Question` objects. Each question can be:
-
-- **Free-text** (`options=None`)
-- **Single-select** (`options=[...]`, `multi_select=False`)
-- **Multi-select** (`options=[...]`, `multi_select=True`)
-- **"Other" with input** (option has `allow_input=True` — user types free text)
-
-```python
-from cubepi.hitl.types import Question, Option
-
-answers = await channel.ask([
- Question(key="framework", prompt="Which framework?", options=[
- Option(label="React", value="react"),
- Option(label="Vue", value="vue"),
- Option(label="Other", value="other", allow_input=True),
- ]),
- Question(key="features", prompt="Enable:", multi_select=True, options=[
- Option(label="Auth", value="auth"),
- Option(label="Payments", value="payments"),
- ]),
-])
-# answers == {"framework": "react", "features": ["auth", "payments"]}
-```
-
-## Timeout
-
-Both channels accept a `default_timeout` constructor arg and every verb
-accepts a per-call `timeout` kwarg (per-call overrides default).
-
-| Layer | API |
-|---|---|
-| Channel constructor | `InMemoryChannel(default_timeout=30.0)` |
-| Per-call override | `channel.confirm("ok?", timeout=10.0)` |
-| Per-call off | `channel.approve(..., timeout=None)` when channel default is set |
-
-Timeout expiry raises `HitlTimedOut(BaseException)` from the agent-side
-`await`. The surrounding tool or middleware translates it to
-`tool_result.is_error=True` with `details["hitl"]["decision"]="timed_out"`,
-so the model sees a clean denial and can react naturally. The envelope's
-`HitlRequest.timeout_seconds` is filled automatically so the frontend can
-render a countdown.
-
-## Built-in middlewares
-
-### `ConfirmToolCallMiddleware`
-
-"Always ask the human for tool *names* in this set."
-
-```python
-from cubepi.hitl import ConfirmToolCallMiddleware
-
-# Set-based matching — only ask for these tool names
-agent = Agent(
- ...,
- middleware=[
- ConfirmToolCallMiddleware(
- channel,
- require_confirm={"bash", "write_file", "http_post"},
- timeout_seconds=180,
- ),
- ],
-)
-```
-
-`require_confirm` options:
-
-| Value | Behavior |
-|---|---|
-| `None` (default) | Confirm **every** tool. |
-| `set[str]` | Confirm if `tool_call.name` is in the set. |
-| `Callable[[BeforeToolCallContext], bool]` | Custom predicate — inspect args, context, etc. |
-
-An optional `details_fn(ctx: BeforeToolCallContext) -> dict` enriches the
-approve request payload with extra context the frontend can render (e.g.
-matched rule name, impact preview, affected file list).
-
-### `ApprovalPolicyMiddleware`
-
-For hosts with a **policy engine** that classifies tool calls into three
-tiers — auto-allow, hard-deny, or human-confirm.
-
-```python
-from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny
-
-def my_policy(ctx):
- if ctx.tool_call.name == "read_file":
- return Approve() # passthrough
- if ctx.tool_call.name.startswith("dangerous_"):
- return Deny(reason="blocked by policy") # hard block, no human asked
- return AskUser(timeout_seconds=180) # human confirm
-
-agent = Agent(
- ...,
- middleware=[ApprovalPolicyMiddleware(channel, policy=my_policy)],
-)
-```
-
-The policy function can be sync or async (`await`-able). It returns one of:
-
-| Return | Effect |
-|---|---|
-| `Approve()` | Tool runs; channel never invoked. |
-| `Deny(reason)` | Tool blocked; `hitl_trace["decision"]="policy_deny"`. |
-| `AskUser(timeout_seconds=..., details=...)` | Channel invoked; human chooses approve/deny/edit. |
-
-Policy-deny and human-deny produce different `hitl_trace` keys (`policy_deny`
-vs `human_deny`) so audit and trace can distinguish them.
-
-## `ask_user` built-in tool
-
-A tool the **model** invokes when it needs structured input from the user.
-The factory returns an `AgentTool` named `"ask_user"` with
-`execution_mode="sequential"` — it can't run in parallel with other tools.
-
-```python
-from cubepi.hitl import ask_user_tool
-
-agent = Agent(
- ...,
- tools=[bash_tool, ask_user_tool(channel)],
-)
-```
-
-The tool description explicitly steers the model away from using `ask_user`
-for free-form clarification ("for free-form questions, end your turn with
-text — the user's next message is your answer"). The model should only
-invoke it when a **structured** answer is needed.
-
-The `Parameters` prompt schema the model sees:
-
-| Field | Type | Description |
-|---|---|---|
-| `questions` | array | One or more question objects. |
-| `questions[].key` | string | Field name in the answer dict. |
-| `questions[].prompt` | string | The question text. |
-| `questions[].options` | array (optional) | Selection options. `None` = free text. |
-| `questions[].options[].label` | string | Human-facing label. |
-| `questions[].options[].value` | string | Value returned to agent. |
-| `questions[].options[].allow_input` | bool (default `false`) | "Other / please specify." |
-| `questions[].multi_select` | bool (default `false`) | Allow multiple selections. |
-| `questions[].required` | bool (default `true`) | Can the user skip this? |
-
-Cancel and timeout are surfaced as `tool_result.is_error=True` with
-`details["hitl"]["outcome"]="cancelled"` / `"timed_out"` — the model sees
-a clean error tool result and can react. Other HITL control exceptions
-(HitlDetached, HitlAborted) propagate to the Agent layer, not the model.
-
-## Cross-process (web service) flow
-
-Full lifecycle of a suspend/resume cycle:
-
-```python
-import asyncio
-from cubepi.agent.agent import Agent
-from cubepi.checkpointer.postgres import PostgresCheckpointer
-from cubepi.hitl import (
- ApproveAnswer, CheckpointedChannel, ConfirmToolCallMiddleware,
-)
-
-# ---------- Process 1: HTTP POST /chat ----------
-
-async with PostgresCheckpointer("postgresql://...") as cp:
- channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
-
- agent = Agent(
- provider=..., model=...,
- tools=[bash_tool],
- middleware=[
- ConfirmToolCallMiddleware(channel, require_confirm={"bash"}),
- ],
- channel=channel,
- checkpointer=cp,
- thread_id="conv-42",
- )
-
- # prompt() blocks until the HITL request is answered OR the host
- # calls detach(). Same-process host coroutines can answer directly
- # via channel.answer(); cross-process hosts use respond().
- task = asyncio.create_task(agent.prompt("delete temp files"))
-
- # Poll for pending (or subscribe to channel for SSE push)
- for _ in range(1000):
- pending = channel.pending
- if pending is not None:
- break
- await asyncio.sleep(0.1)
-
- assert pending is not None
- # Render pending.payload to the frontend (an ApproveRequest:
- # tool_name="bash", args={"cmd":"rm /tmp/foo"}, ...)
-
- # Graceful suspend — persist the assistant message + unresolved
- # tool_calls, keep pending_request in DB, emit AgentSuspendedEvent.
- # The HTTP handler returns 200 { status: "awaiting_approval" }.
- await agent.detach()
- await task # prompt() unwinds with HitlDetached
-
-
-# ---------- Process 2: HTTP POST /respond ----------
-
-async with PostgresCheckpointer("postgresql://...") as cp:
- channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
-
- agent = Agent(
- provider=..., model=...,
- tools=[bash_tool],
- middleware=[
- ConfirmToolCallMiddleware(channel, require_confirm={"bash"}),
- ],
- channel=channel,
- checkpointer=cp,
- thread_id="conv-42",
- )
-
- # Loads the persisted history + pending, validates the question_id
- # matches, attaches the answer to the channel, re-enters the loop
- # where the last assistant message had unresolved tool calls.
- await agent.respond(
- question_id=request.json["call_id"],
- answer=ApproveAnswer(decision="approve"),
- )
- # The bash tool executes, the model receives the tool_result and
- # produces the next assistant turn. Conversation continues normally.
-```
-
-**If the user closes the tab without answering:**
-
-```python
-await agent.abort_pending(reason="user closed tab")
-# Phase 1: signals the in-flight HITL await (if any) to raise HitlAborted.
-# Phase 2: appends synthetic deny ToolResultMessage(s) for unresolved
-# tool_calls, appends a terminal AssistantMessage(stop_reason="aborted"),
-# clears persisted pending, emits AgentAbortedEvent.
-# No model call is made. The conversation is closed.
-```
-
-## Agent API
-
-### Constructor
-
-```python
-Agent(
- ...,
- channel: HitlChannel | None = None, # bind a channel to this agent
-)
-```
-
-If a channel is bound, the Agent wires its `_process_event` as the channel's
-emit callback so `HitlRequestEvent` / `HitlAnswerEvent` are dispatched to all
-agent listeners. A `_run_lock` (`asyncio.Lock`) serialises `prompt`,
-`resume`, and `respond` calls.
-
-### Properties
-
-| Property | Returns | Description |
-|---|---|---|
-| `agent.channel` | `HitlChannel \| None` | The bound channel or `None`. |
-| `agent.in_flight_hitl_request` | `HitlRequest \| None` | The channel's current pending payload. Raises `HitlError` if no channel bound. |
-
-### Methods
-
-| Method | Signature | Description |
-|---|---|---|
-| `load_pending_hitl_request()` | `async → HitlRequest \| None` | Reads the pending from the checkpointer (even post-detach). |
-| `detach()` | `async → None` | Emits `AgentSuspendedEvent(pending_request=...)` then triggers `HitlDetached` on the channel future. The loop exits silently; assistant message retains unresolved tool calls; `pending_request` stays persisted. |
-| `respond(*, question_id=, answer=)` | `async → None` | Resumes a suspended run. Validates qid matches persistent pending, attaches answer to channel, re-enters the loop via `run_agent_loop_resume`. |
-| `abort_pending(reason=)` | `async → None` | Closes the conversation. Two-phase: Phase 1 signals in-flight await (no lock). Phase 2 appends synthetic deny tool_results + terminal `stop_reason="aborted"` assistant (under lock). |
-
-`in_flight_hitl_request` is a synchronous property (reads the in-memory
-channel slot). `load_pending_hitl_request()` is async (reads from the
-checkpointer; useful post-detach or in a fresh process).
-
-## Events
-
-Four new events are emitted on the agent's event stream:
-
-| Event | When | Key fields |
-|---|---|---|
-| `HitlRequestEvent` | Channel receives a new `confirm/approve/ask`. | `request: HitlRequest` |
-| `HitlAnswerEvent` | `channel.answer()` or `channel.cancel()` fires. | `question_id: str`, `answer: Any`, `cancelled: bool`, `timed_out: bool` |
-| `AgentSuspendedEvent` | `agent.detach()` called while HITL was pending. | `pending_request: HitlRequest` |
-| `AgentAbortedEvent` | `agent.abort_pending()` closes the conversation. | `reason: str` |
-
-These are all included in the `AgentEvent` union, so typed listeners
-automatically cover them. `HitlRequestEvent` and `HitlAnswerEvent` are
-emitted by the channel through the agent's emit binding. `AgentSuspendedEvent`
-and `AgentAbortedEvent` are emitted by the Agent layer (not the loop — the
-Agent has the channel handle to populate the real `pending_request` payload).
-
-## Trace spans
-
-When the `cubepi[tracing]` extra is installed, each HITL await is wrapped
-in an OpenTelemetry span:
-
-| Span name | Attributes |
-|---|---|
-| `hitl.approve` | `hitl.tool_name`, `hitl.tool_call_id`, `hitl.outcome`, `hitl.from_resume`, `hitl.duration_seconds` |
-| `hitl.confirm` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
-| `hitl.ask` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
-
-`hitl.outcome` is one of: `approved`, `denied`, `edited`, `answered`,
-`cancelled`, `timed_out`, `aborted`, `detached`.
-
-The tracing import is lazy — if `opentelemetry` is not installed, the
-channel silently falls back to a no-op span.
-
-## Error reference
-
-| Exception | Base class | Meaning |
-|---|---|---|
-| `HitlCancelled(reason)` | `BaseException` | Host called `channel.cancel(qid)`. |
-| `HitlTimedOut(seconds)` | `BaseException` | Per-call or channel-default timeout expired. |
-| `HitlDetached` | `BaseException` | `agent.detach()` called during HITL await. |
-| `HitlAborted` | `BaseException` | `agent.abort_pending()` signalled the agent. |
-| `HitlConcurrencyError` | `Exception` | `confirm/approve/ask` called while channel already has a pending request. |
-| `HitlStaleAnswer` | `Exception` | `channel.answer(qid)` with a `question_id` that doesn't match the current pending. |
-| `HitlNoPendingRequest` | `Exception` | `agent.respond(…)` called but no `pending_request` on the thread. |
-| `HitlDurabilityNotGuaranteed` | `Exception` | Custom tool called `CheckpointedChannel.ask()` without `allow_inside_custom_tool=True`. |
-
-`HitlControlException` (the parent of the four `BaseException` subclasses)
-is intentionally NOT caught by the existing broad `except Exception:` handlers
-in `cubepi.agent.tools._prepare_tool_call` and `_execute_prepared` — this
-mirrors `asyncio.CancelledError`'s pattern.
-
-## When to use `ask_user` vs end of turn
-
-| Goal | Use |
-|---|---|
-| Free-text follow-up question to user | Just end the turn with the question as text; the user's next message is your answer. |
-| Structured selection (one of N) | `ask_user` tool with `options`. |
-| Multi-select ("pick any of") | `ask_user` tool with `multi_select=True`. |
-| "Other" with free-text input | `ask_user` tool option with `allow_input=True`. |
-| Confirm/edit tool args before run | `ConfirmToolCallMiddleware` or `ApprovalPolicyMiddleware`. |
-
-## Durable scope
-
-Durable cross-process resume (survives process death) is supported at two
-well-defined safe suspension points:
-
-1. **`before_tool_call` approval gate** — the approval middleware calls
- `channel.approve(...)` *before* the tool's `execute()` body runs. No tool
- side effects exist yet. Resume re-enters the loop and either runs the
- (possibly edited) tool body or substitutes a synthetic deny tool_result.
-2. **`ask_user` tool body** — whose entire `execute()` body is
- `return await channel.ask(...)`. Resume replays nothing because nothing
- else happened.
-
-**Custom tools that mix HITL with other work inside `execute()` are NOT
-durable cross-process by default.** If such a tool's process dies mid-execute,
-anything that ran before the channel call would be lost. CubePi will raise
-`HitlDurabilityNotGuaranteed` unless the `CheckpointedChannel` is constructed
-with `allow_inside_custom_tool=True` — the caller must acknowledge the
-idempotency contract (the tool body must be a pure HITL wait with no
-preceding observable side effects).
-
-## Testing helpers
-
-```python
-from cubepi.hitl.testing import ScriptedChannel, NoopChannel
-
-# ScriptedChannel: pre-programmed answers, consumed in order.
-ch = ScriptedChannel(answers=[
- ApproveAnswer(decision="approve"),
- {"color": "red"}, # ask answer
- lambda req: ApproveAnswer(decision="deny", reason="test") # callable
-])
-assert len(ch.history) == 3 # all HitlRequests ever seen
-
-# NoopChannel: auto-approves everything. Useful for subagents.
-ch = NoopChannel()
-assert (await ch.approve("bash", "tc", {})).decision == "approve"
-assert (await ch.confirm("?")) is True
-assert await ch.ask([Question(key="k", prompt="p")]) == {"k": ""}
-```
-
-## Architecture notes
-
-- **Single pending per thread.** The agent loop is sequential — at most one
- HITL request is outstanding per `thread_id`. Concurrent `confirm/approve/ask`
- raises `HitlConcurrencyError`.
-- **Prompt-cache prefix invariant.** Between pause and resume, the messages
- list changes only by appending tool-result messages and the next assistant
- turn at the tail. No inserting, reordering, or mutating prior messages —
- that would invalidate the provider-side prompt cache.
-- **`question_id == tool_call_id` for approve requests.** No aliasing or
- mapping needed — hosts that already track `call_id` from the tool stream
- pass it directly.
-- **Resume does not replay.** It re-enters the loop with the answer pre-loaded
- into the channel. The last assistant message's unresolved tool calls dictate
- what executes next. No node-based replay semantics.
diff --git a/website/docs/guides/hitl/durable.md b/website/docs/guides/hitl/durable.md
new file mode 100644
index 0000000..47da37a
--- /dev/null
+++ b/website/docs/guides/hitl/durable.md
@@ -0,0 +1,119 @@
+---
+title: Cross-process & durability
+sidebar_position: 3
+description: "Suspend a CubePi agent on a HITL request and resume it in another process with a CheckpointedChannel; durable-scope rules."
+---
+
+# Cross-process flow & durability
+
+## Cross-process (web service) flow
+
+Full lifecycle of a suspend/resume cycle:
+
+```python
+import asyncio
+from cubepi.agent.agent import Agent
+from cubepi.checkpointer.postgres import PostgresCheckpointer
+from cubepi.hitl import (
+ ApproveAnswer, CheckpointedChannel, ConfirmToolCallMiddleware,
+)
+
+# ---------- Process 1: HTTP POST /chat ----------
+
+async with PostgresCheckpointer("postgresql://...") as cp:
+ channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
+
+ agent = Agent(
+ provider=..., model=...,
+ tools=[bash_tool],
+ middleware=[
+ ConfirmToolCallMiddleware(channel, require_confirm={"bash"}),
+ ],
+ channel=channel,
+ checkpointer=cp,
+ thread_id="conv-42",
+ )
+
+ # prompt() blocks until the HITL request is answered OR the host
+ # calls detach(). Same-process host coroutines can answer directly
+ # via channel.answer(); cross-process hosts use respond().
+ task = asyncio.create_task(agent.prompt("delete temp files"))
+
+ # Poll for pending (or subscribe to channel for SSE push)
+ for _ in range(1000):
+ pending = channel.pending
+ if pending is not None:
+ break
+ await asyncio.sleep(0.1)
+
+ assert pending is not None
+ # Render pending.payload to the frontend (an ApproveRequest:
+ # tool_name="bash", args={"cmd":"rm /tmp/foo"}, ...)
+
+ # Graceful suspend — persist the assistant message + unresolved
+ # tool_calls, keep pending_request in DB, emit AgentSuspendedEvent.
+ # The HTTP handler returns 200 { status: "awaiting_approval" }.
+ await agent.detach()
+ await task # prompt() unwinds with HitlDetached
+
+
+# ---------- Process 2: HTTP POST /respond ----------
+
+async with PostgresCheckpointer("postgresql://...") as cp:
+ channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
+
+ agent = Agent(
+ provider=..., model=...,
+ tools=[bash_tool],
+ middleware=[
+ ConfirmToolCallMiddleware(channel, require_confirm={"bash"}),
+ ],
+ channel=channel,
+ checkpointer=cp,
+ thread_id="conv-42",
+ )
+
+ # Loads the persisted history + pending, validates the question_id
+ # matches, attaches the answer to the channel, re-enters the loop
+ # where the last assistant message had unresolved tool calls.
+ await agent.respond(
+ question_id=request.json["call_id"],
+ answer=ApproveAnswer(decision="approve"),
+ )
+ # The bash tool executes, the model receives the tool_result and
+ # produces the next assistant turn. Conversation continues normally.
+```
+
+**If the user closes the tab without answering:**
+
+```python
+await agent.abort_pending(reason="user closed tab")
+# Phase 1: signals the in-flight HITL await (if any) to raise HitlAborted.
+# Phase 2: appends synthetic deny ToolResultMessage(s) for unresolved
+# tool_calls, appends a terminal AssistantMessage(stop_reason="aborted"),
+# clears persisted pending, emits AgentAbortedEvent.
+# No model call is made. The conversation is closed.
+```
+
+
+## Durable scope
+
+Durable cross-process resume (survives process death) is supported at two
+well-defined safe suspension points:
+
+1. **`before_tool_call` approval gate** — the approval middleware calls
+ `channel.approve(...)` *before* the tool's `execute()` body runs. No tool
+ side effects exist yet. Resume re-enters the loop and either runs the
+ (possibly edited) tool body or substitutes a synthetic deny tool_result.
+2. **`ask_user` tool body** — whose entire `execute()` body is
+ `return await channel.ask(...)`. Resume replays nothing because nothing
+ else happened.
+
+**Custom tools that mix HITL with other work inside `execute()` are NOT
+durable cross-process by default.** If such a tool's process dies mid-execute,
+anything that ran before the channel call would be lost. CubePi will raise
+`HitlDurabilityNotGuaranteed` unless the `CheckpointedChannel` is constructed
+with `allow_inside_custom_tool=True` — the caller must acknowledge the
+idempotency contract (the tool body must be a pure HITL wait with no
+preceding observable side effects).
+
diff --git a/website/docs/guides/hitl/middlewares.md b/website/docs/guides/hitl/middlewares.md
new file mode 100644
index 0000000..1184c41
--- /dev/null
+++ b/website/docs/guides/hitl/middlewares.md
@@ -0,0 +1,124 @@
+---
+title: Middlewares & ask_user
+sidebar_position: 2
+description: "Gate tool calls with ConfirmToolCallMiddleware / ApprovalPolicyMiddleware, and let the model ask structured questions with the ask_user tool."
+---
+
+# Middlewares & the `ask_user` tool
+
+## Built-in middlewares
+
+### `ConfirmToolCallMiddleware`
+
+"Always ask the human for tool *names* in this set."
+
+```python
+from cubepi.hitl import ConfirmToolCallMiddleware
+
+# Set-based matching — only ask for these tool names
+agent = Agent(
+ ...,
+ middleware=[
+ ConfirmToolCallMiddleware(
+ channel,
+ require_confirm={"bash", "write_file", "http_post"},
+ timeout_seconds=180,
+ ),
+ ],
+)
+```
+
+`require_confirm` options:
+
+| Value | Behavior |
+|---|---|
+| `None` (default) | Confirm **every** tool. |
+| `set[str]` | Confirm if `tool_call.name` is in the set. |
+| `Callable[[BeforeToolCallContext], bool]` | Custom predicate — inspect args, context, etc. |
+
+An optional `details_fn(ctx: BeforeToolCallContext) -> dict` enriches the
+approve request payload with extra context the frontend can render (e.g.
+matched rule name, impact preview, affected file list).
+
+### `ApprovalPolicyMiddleware`
+
+For hosts with a **policy engine** that classifies tool calls into three
+tiers — auto-allow, hard-deny, or human-confirm.
+
+```python
+from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny
+
+def my_policy(ctx):
+ if ctx.tool_call.name == "read_file":
+ return Approve() # passthrough
+ if ctx.tool_call.name.startswith("dangerous_"):
+ return Deny(reason="blocked by policy") # hard block, no human asked
+ return AskUser(timeout_seconds=180) # human confirm
+
+agent = Agent(
+ ...,
+ middleware=[ApprovalPolicyMiddleware(channel, policy=my_policy)],
+)
+```
+
+The policy function can be sync or async (`await`-able). It returns one of:
+
+| Return | Effect |
+|---|---|
+| `Approve()` | Tool runs; channel never invoked. |
+| `Deny(reason)` | Tool blocked; `hitl_trace["decision"]="policy_deny"`. |
+| `AskUser(timeout_seconds=..., details=...)` | Channel invoked; human chooses approve/deny/edit. |
+
+Policy-deny and human-deny produce different `hitl_trace` keys (`policy_deny`
+vs `human_deny`) so audit and trace can distinguish them.
+
+## `ask_user` built-in tool
+
+A tool the **model** invokes when it needs structured input from the user.
+The factory returns an `AgentTool` named `"ask_user"` with
+`execution_mode="sequential"` — it can't run in parallel with other tools.
+
+```python
+from cubepi.hitl import ask_user_tool
+
+agent = Agent(
+ ...,
+ tools=[bash_tool, ask_user_tool(channel)],
+)
+```
+
+The tool description explicitly steers the model away from using `ask_user`
+for free-form clarification ("for free-form questions, end your turn with
+text — the user's next message is your answer"). The model should only
+invoke it when a **structured** answer is needed.
+
+The `Parameters` prompt schema the model sees:
+
+| Field | Type | Description |
+|---|---|---|
+| `questions` | array | One or more question objects. |
+| `questions[].key` | string | Field name in the answer dict. |
+| `questions[].prompt` | string | The question text. |
+| `questions[].options` | array (optional) | Selection options. `None` = free text. |
+| `questions[].options[].label` | string | Human-facing label. |
+| `questions[].options[].value` | string | Value returned to agent. |
+| `questions[].options[].allow_input` | bool (default `false`) | "Other / please specify." |
+| `questions[].multi_select` | bool (default `false`) | Allow multiple selections. |
+| `questions[].required` | bool (default `true`) | Can the user skip this? |
+
+Cancel and timeout are surfaced as `tool_result.is_error=True` with
+`details["hitl"]["outcome"]="cancelled"` / `"timed_out"` — the model sees
+a clean error tool result and can react. Other HITL control exceptions
+(HitlDetached, HitlAborted) propagate to the Agent layer, not the model.
+
+
+## When to use `ask_user` vs end of turn
+
+| Goal | Use |
+|---|---|
+| Free-text follow-up question to user | Just end the turn with the question as text; the user's next message is your answer. |
+| Structured selection (one of N) | `ask_user` tool with `options`. |
+| Multi-select ("pick any of") | `ask_user` tool with `multi_select=True`. |
+| "Other" with free-text input | `ask_user` tool option with `allow_input=True`. |
+| Confirm/edit tool args before run | `ConfirmToolCallMiddleware` or `ApprovalPolicyMiddleware`. |
+
diff --git a/website/docs/guides/hitl/overview.md b/website/docs/guides/hitl/overview.md
new file mode 100644
index 0000000..35d95c2
--- /dev/null
+++ b/website/docs/guides/hitl/overview.md
@@ -0,0 +1,171 @@
+---
+title: Overview
+sidebar_position: 1
+description: "CubePi human-in-the-loop: the channel, the three verbs (confirm, approve, ask), and timeouts."
+---
+
+# Human-in-the-Loop (HITL)
+
+CubePi's HITL channel lets an agent **pause and ask a human** before proceeding.
+It handles two recurring patterns with a single primitive:
+
+1. **Sandbox tool confirmation** — a dangerous tool (bash, file writes, API
+ mutations) needs approve / deny / edit from a human before running.
+2. **Mid-run structured questions** — the agent needs a specific selection or
+ form answer from the user before it can continue.
+
+The channel is an `await`-able coroutine collaborator. Tool authors write
+`await channel.ask(...)` and the channel handles the pause. Host code
+(subscribers) renders the pending request and posts an answer. Two backends
+cover the full spectrum:
+
+- `InMemoryChannel` — CLI, notebooks, tests. Process dies, pending is lost.
+- `CheckpointedChannel` — web services. Persists the pending request to a
+ `Checkpointer` so a different process (or the same process after restart)
+ can pick up and answer hours later.
+
+## Architecture
+
+```text
+┌────────────────────────────────────────────────────────┐
+│ Host (cubebox web service / CLI / TUI) │
+│ │
+│ subscribe to channel.pending ◄──── answer / cancel │
+└──────────────────────┬─────────────────────────────────┘
+ │
+ ┌─────────────▼──────────────┐
+ │ HitlChannel (Protocol) │
+ │ confirm / approve / ask │
+ │ pending / answer / cancel │
+ └──────┬──────────────┬──────┘
+ │ │
+ ┌──────────▼───┐ ┌──────▼────────────┐
+ │InMemoryChannel│ │CheckpointedChannel│
+ │ (Future+Queue)│ │ (Future + persi- │
+ │ │ │ sts to Checkpo- │
+ │ │ │ inter) │
+ └───────────────┘ └───────────────────┘
+ │ │
+ │ used by ────┤
+ │ │
+ ┌──────────▼──────────────▼────────────┐
+ │ ask_user tool ConfirmToolCallMW │
+ │ (structured form) (approve/deny/ │
+ │ edit per-tool) │
+ └──────────────────────────────────────┘
+ │
+ ┌─────────────▼──────────────┐
+ │ cubepi Agent loop │
+ │ (BeforeToolCallResult │
+ │ carries hitl_trace) │
+ └────────────────────────────┘
+```
+
+## Channel types
+
+### `InMemoryChannel`
+
+For single-process use. Holds an `asyncio.Future` internally — the host
+calls `channel.answer()` from the same event loop.
+
+```python
+from cubepi.hitl import InMemoryChannel
+
+channel = InMemoryChannel(
+ default_timeout=180.0, # per-call timeout; None = no timeout (default)
+)
+```
+
+### `CheckpointedChannel`
+
+For cross-process use. On every `confirm / approve / ask`, the `HitlRequest`
+is persisted via `Checkpointer.save_pending_request(thread_id, ...)`. On
+`channel.answer()`, the pending is cleared. On `HitlDetached` (graceful
+suspend), the pending stays so a later `Agent.respond()` can resume.
+
+```python
+from cubepi.hitl import CheckpointedChannel
+from cubepi.checkpointer.sqlite import SQLiteCheckpointer # or postgres / mysql
+
+async with SQLiteCheckpointer("path/to.db") as cp:
+ channel = CheckpointedChannel(
+ checkpointer=cp,
+ thread_id="conversation-42",
+ default_timeout=None, # cross-process: typical to disable
+ allow_inside_custom_tool=False, # safety gate (see Cross-process & durability)
+ )
+```
+
+`CheckpointedChannel.__init__` validates the checkpointer implements
+`save_pending_request` and `load_pending_request` — it fails early with
+`HitlError` if not.
+
+## The three verbs
+
+### `confirm(prompt, *, details, timeout, signal) → bool`
+
+A simple yes/no question. The host answers `True` or `False`.
+
+```python
+if await channel.confirm("Deploy to production?", details={"env": "prod"}):
+ await deploy()
+```
+
+### `approve(tool_name, tool_call_id, args, *, details, timeout, signal) → ApproveAnswer`
+
+The sandbox-confirm verb. Returns an `ApproveAnswer` with one of three decisions:
+
+| Decision | Result |
+|---|---|
+| `"approve"` | Tool runs with the original args. |
+| `"deny"` | Tool is blocked; `tool_result.is_error=True` with `details["hitl"]["decision"]="human_deny"`. |
+| `"edit"` | Tool runs with the edited args (re-validated against the tool's pydantic parameter model). |
+
+For `approve` requests, the envelope's `question_id` is set to the LLM's
+`tool_call_id` — no separate UUID, so host code can correlate by the same
+ID it already tracks from the tool stream.
+
+### `ask(questions, *, timeout, signal) → dict[str, str | list[str]]`
+
+A structured form with one or more `Question` objects. Each question can be:
+
+- **Free-text** (`options=None`)
+- **Single-select** (`options=[...]`, `multi_select=False`)
+- **Multi-select** (`options=[...]`, `multi_select=True`)
+- **"Other" with input** (option has `allow_input=True` — user types free text)
+
+```python
+from cubepi.hitl.types import Question, Option
+
+answers = await channel.ask([
+ Question(key="framework", prompt="Which framework?", options=[
+ Option(label="React", value="react"),
+ Option(label="Vue", value="vue"),
+ Option(label="Other", value="other", allow_input=True),
+ ]),
+ Question(key="features", prompt="Enable:", multi_select=True, options=[
+ Option(label="Auth", value="auth"),
+ Option(label="Payments", value="payments"),
+ ]),
+])
+# answers == {"framework": "react", "features": ["auth", "payments"]}
+```
+
+## Timeout
+
+Both channels accept a `default_timeout` constructor arg and every verb
+accepts a per-call `timeout` kwarg (per-call overrides default).
+
+| Layer | API |
+|---|---|
+| Channel constructor | `InMemoryChannel(default_timeout=30.0)` |
+| Per-call override | `channel.confirm("ok?", timeout=10.0)` |
+| Per-call off | `channel.approve(..., timeout=None)` when channel default is set |
+
+Timeout expiry raises `HitlTimedOut(BaseException)` from the agent-side
+`await`. The surrounding tool or middleware translates it to
+`tool_result.is_error=True` with `details["hitl"]["decision"]="timed_out"`,
+so the model sees a clean denial and can react naturally. The envelope's
+`HitlRequest.timeout_seconds` is filled automatically so the frontend can
+render a countdown.
+
diff --git a/website/docs/guides/hitl/reference.md b/website/docs/guides/hitl/reference.md
new file mode 100644
index 0000000..345a0fb
--- /dev/null
+++ b/website/docs/guides/hitl/reference.md
@@ -0,0 +1,132 @@
+---
+title: API, events & reference
+sidebar_position: 4
+description: "CubePi HITL reference: Agent API, events, trace spans, error reference, testing helpers, and architecture notes."
+---
+
+# API, events & reference
+
+## Agent API
+
+### Constructor
+
+```python
+Agent(
+ ...,
+ channel: HitlChannel | None = None, # bind a channel to this agent
+)
+```
+
+If a channel is bound, the Agent wires its `_process_event` as the channel's
+emit callback so `HitlRequestEvent` / `HitlAnswerEvent` are dispatched to all
+agent listeners. A `_run_lock` (`asyncio.Lock`) serialises `prompt`,
+`resume`, and `respond` calls.
+
+### Properties
+
+| Property | Returns | Description |
+|---|---|---|
+| `agent.channel` | `HitlChannel \| None` | The bound channel or `None`. |
+| `agent.in_flight_hitl_request` | `HitlRequest \| None` | The channel's current pending payload. Raises `HitlError` if no channel bound. |
+
+### Methods
+
+| Method | Signature | Description |
+|---|---|---|
+| `load_pending_hitl_request()` | `async → HitlRequest \| None` | Reads the pending from the checkpointer (even post-detach). |
+| `detach()` | `async → None` | Emits `AgentSuspendedEvent(pending_request=...)` then triggers `HitlDetached` on the channel future. The loop exits silently; assistant message retains unresolved tool calls; `pending_request` stays persisted. |
+| `respond(*, question_id=, answer=)` | `async → None` | Resumes a suspended run. Validates qid matches persistent pending, attaches answer to channel, re-enters the loop via `run_agent_loop_resume`. |
+| `abort_pending(reason=)` | `async → None` | Closes the conversation. Two-phase: Phase 1 signals in-flight await (no lock). Phase 2 appends synthetic deny tool_results + terminal `stop_reason="aborted"` assistant (under lock). |
+
+`in_flight_hitl_request` is a synchronous property (reads the in-memory
+channel slot). `load_pending_hitl_request()` is async (reads from the
+checkpointer; useful post-detach or in a fresh process).
+
+## Events
+
+Four new events are emitted on the agent's event stream:
+
+| Event | When | Key fields |
+|---|---|---|
+| `HitlRequestEvent` | Channel receives a new `confirm/approve/ask`. | `request: HitlRequest` |
+| `HitlAnswerEvent` | `channel.answer()` or `channel.cancel()` fires. | `question_id: str`, `answer: Any`, `cancelled: bool`, `timed_out: bool` |
+| `AgentSuspendedEvent` | `agent.detach()` called while HITL was pending. | `pending_request: HitlRequest` |
+| `AgentAbortedEvent` | `agent.abort_pending()` closes the conversation. | `reason: str` |
+
+These are all included in the `AgentEvent` union, so typed listeners
+automatically cover them. `HitlRequestEvent` and `HitlAnswerEvent` are
+emitted by the channel through the agent's emit binding. `AgentSuspendedEvent`
+and `AgentAbortedEvent` are emitted by the Agent layer (not the loop — the
+Agent has the channel handle to populate the real `pending_request` payload).
+
+## Trace spans
+
+When the `cubepi[tracing]` extra is installed, each HITL await is wrapped
+in an OpenTelemetry span:
+
+| Span name | Attributes |
+|---|---|
+| `hitl.approve` | `hitl.tool_name`, `hitl.tool_call_id`, `hitl.outcome`, `hitl.from_resume`, `hitl.duration_seconds` |
+| `hitl.confirm` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
+| `hitl.ask` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
+
+`hitl.outcome` is one of: `approved`, `denied`, `edited`, `answered`,
+`cancelled`, `timed_out`, `aborted`, `detached`.
+
+The tracing import is lazy — if `opentelemetry` is not installed, the
+channel silently falls back to a no-op span.
+
+## Error reference
+
+| Exception | Base class | Meaning |
+|---|---|---|
+| `HitlCancelled(reason)` | `BaseException` | Host called `channel.cancel(qid)`. |
+| `HitlTimedOut(seconds)` | `BaseException` | Per-call or channel-default timeout expired. |
+| `HitlDetached` | `BaseException` | `agent.detach()` called during HITL await. |
+| `HitlAborted` | `BaseException` | `agent.abort_pending()` signalled the agent. |
+| `HitlConcurrencyError` | `Exception` | `confirm/approve/ask` called while channel already has a pending request. |
+| `HitlStaleAnswer` | `Exception` | `channel.answer(qid)` with a `question_id` that doesn't match the current pending. |
+| `HitlNoPendingRequest` | `Exception` | `agent.respond(…)` called but no `pending_request` on the thread. |
+| `HitlDurabilityNotGuaranteed` | `Exception` | Custom tool called `CheckpointedChannel.ask()` without `allow_inside_custom_tool=True`. |
+
+`HitlControlException` (the parent of the four `BaseException` subclasses)
+is intentionally NOT caught by the existing broad `except Exception:` handlers
+in `cubepi.agent.tools._prepare_tool_call` and `_execute_prepared` — this
+mirrors `asyncio.CancelledError`'s pattern.
+
+
+## Testing helpers
+
+```python
+from cubepi.hitl.testing import ScriptedChannel, NoopChannel
+
+# ScriptedChannel: pre-programmed answers, consumed in order.
+ch = ScriptedChannel(answers=[
+ ApproveAnswer(decision="approve"),
+ {"color": "red"}, # ask answer
+ lambda req: ApproveAnswer(decision="deny", reason="test") # callable
+])
+assert len(ch.history) == 3 # all HitlRequests ever seen
+
+# NoopChannel: auto-approves everything. Useful for subagents.
+ch = NoopChannel()
+assert (await ch.approve("bash", "tc", {})).decision == "approve"
+assert (await ch.confirm("?")) is True
+assert await ch.ask([Question(key="k", prompt="p")]) == {"k": ""}
+```
+
+## Architecture notes
+
+- **Single pending per thread.** The agent loop is sequential — at most one
+ HITL request is outstanding per `thread_id`. Concurrent `confirm/approve/ask`
+ raises `HitlConcurrencyError`.
+- **Prompt-cache prefix invariant.** Between pause and resume, the messages
+ list changes only by appending tool-result messages and the next assistant
+ turn at the tail. No inserting, reordering, or mutating prior messages —
+ that would invalidate the provider-side prompt cache.
+- **`question_id == tool_call_id` for approve requests.** No aliasing or
+ mapping needed — hosts that already track `call_id` from the tool stream
+ pass it directly.
+- **Resume does not replay.** It re-enters the loop with the answer pre-loaded
+ into the channel. The last assistant message's unresolved tool calls dictate
+ what executes next. No node-based replay semantics.
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl.md
deleted file mode 100644
index b7db040..0000000
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl.md
+++ /dev/null
@@ -1,334 +0,0 @@
----
-title: 人机协同 (HITL)
-description: "通过 confirm、approve 和 ask 三种动词为 CubePi agent 添加人机协同暂停能力。"
-sidebar_position: 10
----
-
-# 人机协同 (HITL)
-
-CubePi 的 HITL channel 让 agent 能够**暂停并等待人类输入**后再继续。
-它用一个统一原语覆盖两种典型模式:
-
-1. **沙箱工具确认** —— 危险工具(bash、文件写入、API 变更)在运行前
- 需要人类 approve / deny / edit。
-2. **运行中结构化提问** —— agent 需要用户做出选择或填写表单才能继续。
-
-Channel 是一个可 `await` 的协程协作者。工具作者写
-`await channel.ask(...)`,channel 处理暂停。宿主代码订阅挂起请求并回填
-答案。两种后端覆盖全场景:
-
-- `InMemoryChannel` —— CLI、notebook、测试。进程死亡,挂起丢失。
-- `CheckpointedChannel` —— web 服务。将挂起请求持久化到 `Checkpointer`,
- 让不同进程(或重启后的同一进程)在数小时后拾起并回答。
-
-## 三种动词
-
-### `confirm(prompt, *, details, timeout, signal) → bool`
-
-简单的 yes/no 问题。宿主回答 `True` 或 `False`。
-
-### `approve(tool_name, tool_call_id, args, *, details, timeout, signal) → ApproveAnswer`
-
-沙箱确认动词。返回一个 `ApproveAnswer`,三种决策:
-
-| 决策 | 结果 |
-|---|---|
-| `"approve"` | 以原始参数运行工具 |
-| `"deny"` | 阻塞工具;`tool_result.is_error=True`,`details["hitl"]["decision"]="human_deny"` |
-| `"edit"` | 以编辑后的参数运行(会拿工具的 pydantic 参数模型重新校验) |
-
-对 `approve` 请求,信封的 `question_id` 设为 LLM 的 `tool_call_id` —
-没有独立的 UUID,所以宿主代码可以直接用它已经在工具流中追踪的同一个
-ID 来关联。
-
-### `ask(questions, *, timeout, signal) → dict[str, str | list[str]]`
-
-一个包含一个或多个 `Question` 对象的结构化表单。每个问题可以是:
-
-- **自由文本** (`options=None`)
-- **单选** (`options=[...]`, `multi_select=False`)
-- **多选** (`options=[...]`, `multi_select=True`)
-- **"其他" 可输入**(选项有 `allow_input=True` —— 用户输入自由文本)
-
-```python
-from cubepi.hitl.types import Question, Option
-
-answers = await channel.ask([
- Question(key="framework", prompt="选择框架?", options=[
- Option(label="React", value="react"),
- Option(label="Vue", value="vue"),
- Option(label="其他", value="other", allow_input=True),
- ]),
- Question(key="features", prompt="启用功能:", multi_select=True, options=[
- Option(label="认证", value="auth"),
- Option(label="支付", value="payments"),
- ]),
-])
-# answers == {"framework": "react", "features": ["auth", "payments"]}
-```
-
-## 超时
-
-两个 channel 都在构造函数接受 `default_timeout`,每个动词接受一個
-per-call 的 `timeout` kwarg(per-call 覆盖默认)。
-
-超时到期从 agent 侧的 `await` 抛出 `HitlTimedOut(BaseException)`。
-周围的工具或中间件将其转换为 `tool_result.is_error=True`,
-`details["hitl"]["decision"]="timed_out"`,模型看到干净的拒绝结果
-并能自然反应。信封的 `HitlRequest.timeout_seconds` 会自动填写,
-前端可以渲染倒计时。
-
-## 内置中间件
-
-### `ConfirmToolCallMiddleware`
-
-"在集合中的工具名一律询问人类。"
-
-```python
-from cubepi.hitl import ConfirmToolCallMiddleware
-
-agent = Agent(
- ...,
- middleware=[
- ConfirmToolCallMiddleware(
- channel,
- require_confirm={"bash", "write_file"},
- timeout_seconds=180,
- ),
- ],
-)
-```
-
-`require_confirm` 选项:
-
-| 值 | 行为 |
-|---|---|
-| `None`(默认) | 确认**所有**工具 |
-| `set[str]` | 仅当 `tool_call.name` 在集合中时确认 |
-| `Callable[[BeforeToolCallContext], bool]` | 自定义断言 —— 检查参数、上下文等 |
-
-### `ApprovalPolicyMiddleware`
-
-适用于需要**策略引擎**将工具调用分为 auto-allow、hard-deny 和
-human-confirm 三类的宿主。
-
-```python
-from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny
-
-def my_policy(ctx):
- if ctx.tool_call.name == "read_file":
- return Approve() # 直接放行
- if ctx.tool_call.name.startswith("dangerous_"):
- return Deny(reason="策略阻止") # 硬阻止,不询问人类
- return AskUser(timeout_seconds=180) # 人类确认
-
-agent = Agent(
- ...,
- middleware=[ApprovalPolicyMiddleware(channel, policy=my_policy)],
-)
-```
-
-策略函数可以是同步或异步(可 `await`)。返回值:
-
-| 返回 | 效果 |
-|---|---|
-| `Approve()` | 工具运行;channel 从未调用 |
-| `Deny(reason)` | 工具阻塞;`hitl_trace["decision"]="policy_deny"` |
-| `AskUser(timeout_seconds=..., details=...)` | 调用 channel;人类选择 approve/deny/edit |
-
-## `ask_user` 内置工具
-
-模型在需要用户结构化输入时调用的工具。工厂函数返回一个名为
-`"ask_user"` 的 `AgentTool`,`execution_mode="sequential"`。
-
-```python
-from cubepi.hitl import ask_user_tool
-
-agent = Agent(
- ...,
- tools=[bash_tool, ask_user_tool(channel)],
-)
-```
-
-工具描述明确引导模型不要拿 `ask_user` 做自由文本澄清("对于自由文本
-提问,直接用文本结束 turn——用户的下一条消息就是答案")。
-
-取消和超时以 `tool_result.is_error=True` 体现,
-`details["hitl"]["outcome"]="cancelled"` / `"timed_out"` —— 模型看到
-干净的���误工具结果并能做出反应。其他 HITL 控制异常(HitlDetached、
-HitlAborted)传播到 Agent 层,不暴露给模型。
-
-## 跨进程(web 服务)流程
-
-```python
-# ───── 进程 1:HTTP POST /chat ─────
-
-async with PostgresCheckpointer("postgresql://...") as cp:
- channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
-
- agent = Agent(
- provider=…, model=…,
- tools=[bash_tool],
- middleware=[ConfirmToolCallMiddleware(channel, require_confirm={"bash"})],
- channel=channel, checkpointer=cp, thread_id="conv-42",
- )
-
- task = asyncio.create_task(agent.prompt("删除临时文件"))
-
- # 轮询挂起(或订阅 channel 用于 SSE 推送)
- for _ in range(1000):
- pending = channel.pending
- if pending is not None:
- break
- await asyncio.sleep(0.1)
-
- # 优雅挂起 — 持久化 assistant message + 未决 tool_calls,
- # pending_request 留在 DB, 发射 AgentSuspendedEvent.
- await agent.detach()
- await task
-
-
-# ───── 进程 2:HTTP POST /respond ─────
-
-async with PostgresCheckpointer("postgresql://...") as cp:
- channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
-
- agent = Agent(
- provider=…, model=…,
- tools=[bash_tool],
- middleware=[ConfirmToolCallMiddleware(channel, require_confirm={"bash"})],
- channel=channel, checkpointer=cp, thread_id="conv-42",
- )
-
- await agent.respond(
- question_id=request.json["call_id"],
- answer=ApproveAnswer(decision="approve"),
- )
- # Bash 工具执行,模型收到 tool_result,产生下一个 assistant turn。
-```
-
-**用户关闭 tab 未回答时:**
-
-```python
-await agent.abort_pending(reason="用户关闭了 tab")
-# Phase 1:发信号给进行中的 HITL await(如有),触发 HitlAborted。
-# Phase 2:为未决的 tool_calls 追加合成 deny ToolResultMessage,
-# 追加终止 AssistantMessage(stop_reason="aborted"),
-# 清除持久化 pending, 发射 AgentAbortedEvent。
-# 不调用模型。对话关闭。
-```
-
-## Agent API
-
-| 属性/方法 | 签名 | 说明 |
-|---|---|---|
-| `agent.channel` | `HitlChannel \| None` | 绑定的 channel 或 `None` |
-| `agent.in_flight_hitl_request` | `HitlRequest \| None` | channel 当前 pending(同步属性) |
-| `load_pending_hitl_request()` | `async → HitlRequest \| None` | 从 checkpointer 读取 pending(detach 后也能用) |
-| `detach()` | `async → None` | 发射 `AgentSuspendedEvent` 然后触发 `HitlDetached` |
-| `respond(*, question_id=, answer=)` | `async → None` | 恢复挂起的运行 |
-| `abort_pending(reason=)` | `async → None` | 关闭对话(两阶段:发信号 + 追加合成拒绝) |
-
-## 事件
-
-四个新事件在 agent 事件流上发射:
-
-| 事件 | 何时发射 | 关键字段 |
-|---|---|---|
-| `HitlRequestEvent` | channel 收到新的 `confirm/approve/ask` | `request: HitlRequest` |
-| `HitlAnswerEvent` | `channel.answer()` 或 `channel.cancel()` 触发 | `question_id`, `answer`, `cancelled`, `timed_out` |
-| `AgentSuspendedEvent` | `agent.detach()` 被调用时 HITL pending | `pending_request: HitlRequest` |
-| `AgentAbortedEvent` | `agent.abort_pending()` 关闭对话 | `reason: str` |
-
-## 追踪 span
-
-安装 `cubepi[tracing]` extra 后,每次 HITL await 都会包装在一个
-OpenTelemetry span 中:
-
-| Span 名称 | 属性 |
-|---|---|
-| `hitl.approve` | `hitl.tool_name`, `hitl.tool_call_id`, `hitl.outcome`, `hitl.from_resume`, `hitl.duration_seconds` |
-| `hitl.confirm` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
-| `hitl.ask` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
-
-`hitl.outcome` 可以是:`approved`, `denied`, `edited`, `answered`,
-`cancelled`, `timed_out`, `aborted`, `detached`。
-
-追踪导入是懒式的 —— 未安装 `opentelemetry` 时,channel 静默回退到
-无操作 span。
-
-## 错误参考
-
-| 异常 | 基类 | 含义 |
-|---|---|---|
-| `HitlCancelled(reason)` | `BaseException` | 宿主调了 `channel.cancel(qid)` |
-| `HitlTimedOut(seconds)` | `BaseException` | per-call 或 channel 默认超时到期 |
-| `HitlDetached` | `BaseException` | HITL await 期间调了 `agent.detach()` |
-| `HitlAborted` | `BaseException` | `agent.abort_pending()` 向 agent 发信号 |
-| `HitlConcurrencyError` | `Exception` | channel 已有 pending 时再次调用 `confirm/approve/ask` |
-| `HitlStaleAnswer` | `Exception` | `channel.answer(qid)` 的 qid 与当前 pending 不匹配 |
-| `HitlNoPendingRequest` | `Exception` | 调了 `agent.respond(…)` 但线程没有 `pending_request` |
-| `HitlDurabilityNotGuaranteed` | `Exception` | 自定义工具调了 `CheckpointedChannel.ask()` 但没有 `allow_inside_custom_tool=True` |
-
-`HitlControlException`(四个 `BaseException` 子类的父类)**故意**不被
-`cubepi.agent.tools._prepare_tool_call` 和 `_execute_prepared` 中现有
-的广泛 `except Exception:` 处理器捕获 —— 这模仿了 `asyncio.CancelledError`
-的模式。
-
-## `ask_user` 对比 end of turn
-
-| 目标 | 用法 |
-|---|---|
-| 对用户的自由文本追问 | 直接用文本结束 turn——用户的下一条消息就是答案 |
-| 结构化选择 (N 选一) | `ask_user` 工具带 `options` |
-| 多选 ("任意选择") | `ask_user` 工具带 `multi_select=True` |
-| "其他" 可自由文本输入 | `ask_user` 工具选项带 `allow_input=True` |
-| 确认/编辑工具参数后才运行 | `ConfirmToolCallMiddleware` 或 `ApprovalPolicyMiddleware` |
-
-## 持久化范围
-
-持久的跨进程恢复(进程死亡后仍能继续)在两个定义明确的安全暂停点支持:
-
-1. **`before_tool_call` 确认门** —— 确认中间件在工具的 `execute()` body
- 运行*之前*调用 `channel.approve(...)`。此时不存在工具副作用。恢复时
- 重新进入循环,执行(可能被编辑过的)工具体或替换为合成 deny
- tool_result。
-2. **`ask_user` 工具体** —— 其整个 `execute()` body 就是
- `return await channel.ask(...)`。恢复时不会重放任何内容。
-
-**默认情况下,在 `execute()` 内将 HITL 与其他工作混合的自定义工具不
-支持跨进程持久化。** 如果此类工具的进程在执行中途死亡,channel 调用
-前运行的所有内容都会丢失。除非使用 `allow_inside_custom_tool=True`
-构造 `CheckpointedChannel`,否则将抛出 `HitlDurabilityNotGuaranteed` —
-调用者必须承认等幂性契约(工具体在这一点必须是纯 HITL 等待,前面没有
-可观察的副作用)。
-
-## 测试辅助
-
-```python
-from cubepi.hitl.testing import ScriptedChannel, NoopChannel
-
-# ScriptedChannel:预编程答案,按顺序消费
-ch = ScriptedChannel(answers=[
- ApproveAnswer(decision="approve"),
- {"color": "red"}, # ask 答案
-])
-assert len(ch.history) == 2 # 所有见过的 HitlRequest
-
-# NoopChannel:自动批准一切。用于测试中的 subagent。
-ch = NoopChannel()
-assert (await ch.approve("bash", "tc", {})).decision == "approve"
-```
-
-## 架构说明
-
-- **每线程单一 pending。** Agent 循环是顺序的——每个 `thread_id` 最多
- 有一个 HITL 请求。并发 `confirm/approve/ask` 会抛 `HitlConcurrencyError`。
-- **Prompt-cache 前缀不变量。** 暂停与恢复之间,消息列表仅通过在末尾
- 追加 tool-result 消息和下一条 assistant turn 来改变。不插入、重排或
- 修改先前的消息——否则会使 provider 端的 prompt cache 失效。
-- **`question_id == tool_call_id` 适用于 approve 请求。** 无需别名或
- 映射——已从工具流中追踪 `call_id` 的宿主可直接传递。
-- **恢复不重放。** 恢复时将答案预加载到 channel 并重新进入循环。最后一条
- assistant message 中未决的 tool call 决定了接下来执行什么。没有基于
- 节点的重放语义。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/durable.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/durable.md
new file mode 100644
index 0000000..5d70035
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/durable.md
@@ -0,0 +1,87 @@
+---
+title: 跨进程与持久化
+sidebar_position: 3
+description: "用 CheckpointedChannel 在一个进程挂起 HITL 请求、在另一个进程恢复;持久化范围规则。"
+---
+
+# 跨进程流程与持久化
+
+## 跨进程(web 服务)流程
+
+```python
+# ───── 进程 1:HTTP POST /chat ─────
+
+async with PostgresCheckpointer("postgresql://...") as cp:
+ channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
+
+ agent = Agent(
+ provider=…, model=…,
+ tools=[bash_tool],
+ middleware=[ConfirmToolCallMiddleware(channel, require_confirm={"bash"})],
+ channel=channel, checkpointer=cp, thread_id="conv-42",
+ )
+
+ task = asyncio.create_task(agent.prompt("删除临时文件"))
+
+ # 轮询挂起(或订阅 channel 用于 SSE 推送)
+ for _ in range(1000):
+ pending = channel.pending
+ if pending is not None:
+ break
+ await asyncio.sleep(0.1)
+
+ # 优雅挂起 — 持久化 assistant message + 未决 tool_calls,
+ # pending_request 留在 DB, 发射 AgentSuspendedEvent.
+ await agent.detach()
+ await task
+
+
+# ───── 进程 2:HTTP POST /respond ─────
+
+async with PostgresCheckpointer("postgresql://...") as cp:
+ channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
+
+ agent = Agent(
+ provider=…, model=…,
+ tools=[bash_tool],
+ middleware=[ConfirmToolCallMiddleware(channel, require_confirm={"bash"})],
+ channel=channel, checkpointer=cp, thread_id="conv-42",
+ )
+
+ await agent.respond(
+ question_id=request.json["call_id"],
+ answer=ApproveAnswer(decision="approve"),
+ )
+ # Bash 工具执行,模型收到 tool_result,产生下一个 assistant turn。
+```
+
+**用户关闭 tab 未回答时:**
+
+```python
+await agent.abort_pending(reason="用户关闭了 tab")
+# Phase 1:发信号给进行中的 HITL await(如有),触发 HitlAborted。
+# Phase 2:为未决的 tool_calls 追加合成 deny ToolResultMessage,
+# 追加终止 AssistantMessage(stop_reason="aborted"),
+# 清除持久化 pending, 发射 AgentAbortedEvent。
+# 不调用模型。对话关闭。
+```
+
+
+## 持久化范围
+
+持久的跨进程恢复(进程死亡后仍能继续)在两个定义明确的安全暂停点支持:
+
+1. **`before_tool_call` 确认门** —— 确认中间件在工具的 `execute()` body
+ 运行*之前*调用 `channel.approve(...)`。此时不存在工具副作用。恢复时
+ 重新进入循环,执行(可能被编辑过的)工具体或替换为合成 deny
+ tool_result。
+2. **`ask_user` 工具体** —— 其整个 `execute()` body 就是
+ `return await channel.ask(...)`。恢复时不会重放任何内容。
+
+**默认情况下,在 `execute()` 内将 HITL 与其他工作混合的自定义工具不
+支持跨进程持久化。** 如果此类工具的进程在执行中途死亡,channel 调用
+前运行的所有内容都会丢失。除非使用 `allow_inside_custom_tool=True`
+构造 `CheckpointedChannel`,否则将抛出 `HitlDurabilityNotGuaranteed` —
+调用者必须承认等幂性契约(工具体在这一点必须是纯 HITL 等待,前面没有
+可观察的副作用)。
+
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/middlewares.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/middlewares.md
new file mode 100644
index 0000000..4076a0f
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/middlewares.md
@@ -0,0 +1,99 @@
+---
+title: 中间件与 ask_user
+sidebar_position: 2
+description: "用 ConfirmToolCallMiddleware / ApprovalPolicyMiddleware 把关工具调用,并用 ask_user 工具让模型发起结构化提问。"
+---
+
+# 中间件与 工具
+
+## 内置中间件
+
+### `ConfirmToolCallMiddleware`
+
+"在集合中的工具名一律询问人类。"
+
+```python
+from cubepi.hitl import ConfirmToolCallMiddleware
+
+agent = Agent(
+ ...,
+ middleware=[
+ ConfirmToolCallMiddleware(
+ channel,
+ require_confirm={"bash", "write_file"},
+ timeout_seconds=180,
+ ),
+ ],
+)
+```
+
+`require_confirm` 选项:
+
+| 值 | 行为 |
+|---|---|
+| `None`(默认) | 确认**所有**工具 |
+| `set[str]` | 仅当 `tool_call.name` 在集合中时确认 |
+| `Callable[[BeforeToolCallContext], bool]` | 自定义断言 —— 检查参数、上下文等 |
+
+### `ApprovalPolicyMiddleware`
+
+适用于需要**策略引擎**将工具调用分为 auto-allow、hard-deny 和
+human-confirm 三类的宿主。
+
+```python
+from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny
+
+def my_policy(ctx):
+ if ctx.tool_call.name == "read_file":
+ return Approve() # 直接放行
+ if ctx.tool_call.name.startswith("dangerous_"):
+ return Deny(reason="策略阻止") # 硬阻止,不询问人类
+ return AskUser(timeout_seconds=180) # 人类确认
+
+agent = Agent(
+ ...,
+ middleware=[ApprovalPolicyMiddleware(channel, policy=my_policy)],
+)
+```
+
+策略函数可以是同步或异步(可 `await`)。返回值:
+
+| 返回 | 效果 |
+|---|---|
+| `Approve()` | 工具运行;channel 从未调用 |
+| `Deny(reason)` | 工具阻塞;`hitl_trace["decision"]="policy_deny"` |
+| `AskUser(timeout_seconds=..., details=...)` | 调用 channel;人类选择 approve/deny/edit |
+
+## `ask_user` 内置工具
+
+模型在需要用户结构化输入时调用的工具。工厂函数返回一个名为
+`"ask_user"` 的 `AgentTool`,`execution_mode="sequential"`。
+
+```python
+from cubepi.hitl import ask_user_tool
+
+agent = Agent(
+ ...,
+ tools=[bash_tool, ask_user_tool(channel)],
+)
+```
+
+工具描述明确引导模型不要拿 `ask_user` 做自由文本澄清("对于自由文本
+提问,直接用文本结束 turn——用户的下一条消息就是答案")。
+
+取消和超时以 `tool_result.is_error=True` 体现,
+`details["hitl"]["outcome"]="cancelled"` / `"timed_out"` —— 模型看到
+干净的���误工具结果并能做出反应。其他 HITL 控制异常(HitlDetached、
+HitlAborted)传播到 Agent 层,不暴露给模型。
+
+
+## `ask_user` 对比 end of turn
+
+| 目标 | 用法 |
+|---|---|
+| 对用户的自由文本追问 | 直接用文本结束 turn——用户的下一条消息就是答案 |
+| 结构化选择 (N 选一) | `ask_user` 工具带 `options` |
+| 多选 ("任意选择") | `ask_user` 工具带 `multi_select=True` |
+| "其他" 可自由文本输入 | `ask_user` 工具选项带 `allow_input=True` |
+| 确认/编辑工具参数后才运行 | `ConfirmToolCallMiddleware` 或 `ApprovalPolicyMiddleware` |
+
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/overview.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/overview.md
new file mode 100644
index 0000000..5ceb0f6
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/overview.md
@@ -0,0 +1,80 @@
+---
+title: 概览
+sidebar_position: 1
+description: "CubePi 人机协同:channel、三种动词(confirm、approve、ask)与超时。"
+---
+
+# 人机协同 (HITL)
+
+CubePi 的 HITL channel 让 agent 能够**暂停并等待人类输入**后再继续。
+它用一个统一原语覆盖两种典型模式:
+
+1. **沙箱工具确认** —— 危险工具(bash、文件写入、API 变更)在运行前
+ 需要人类 approve / deny / edit。
+2. **运行中结构化提问** —— agent 需要用户做出选择或填写表单才能继续。
+
+Channel 是一个可 `await` 的协程协作者。工具作者写
+`await channel.ask(...)`,channel 处理暂停。宿主代码订阅挂起请求并回填
+答案。两种后端覆盖全场景:
+
+- `InMemoryChannel` —— CLI、notebook、测试。进程死亡,挂起丢失。
+- `CheckpointedChannel` —— web 服务。将挂起请求持久化到 `Checkpointer`,
+ 让不同进程(或重启后的同一进程)在数小时后拾起并回答。
+
+## 三种动词
+
+### `confirm(prompt, *, details, timeout, signal) → bool`
+
+简单的 yes/no 问题。宿主回答 `True` 或 `False`。
+
+### `approve(tool_name, tool_call_id, args, *, details, timeout, signal) → ApproveAnswer`
+
+沙箱确认动词。返回一个 `ApproveAnswer`,三种决策:
+
+| 决策 | 结果 |
+|---|---|
+| `"approve"` | 以原始参数运行工具 |
+| `"deny"` | 阻塞工具;`tool_result.is_error=True`,`details["hitl"]["decision"]="human_deny"` |
+| `"edit"` | 以编辑后的参数运行(会拿工具的 pydantic 参数模型重新校验) |
+
+对 `approve` 请求,信封的 `question_id` 设为 LLM 的 `tool_call_id` —
+没有独立的 UUID,所以宿主代码可以直接用它已经在工具流中追踪的同一个
+ID 来关联。
+
+### `ask(questions, *, timeout, signal) → dict[str, str | list[str]]`
+
+一个包含一个或多个 `Question` 对象的结构化表单。每个问题可以是:
+
+- **自由文本** (`options=None`)
+- **单选** (`options=[...]`, `multi_select=False`)
+- **多选** (`options=[...]`, `multi_select=True`)
+- **"其他" 可输入**(选项有 `allow_input=True` —— 用户输入自由文本)
+
+```python
+from cubepi.hitl.types import Question, Option
+
+answers = await channel.ask([
+ Question(key="framework", prompt="选择框架?", options=[
+ Option(label="React", value="react"),
+ Option(label="Vue", value="vue"),
+ Option(label="其他", value="other", allow_input=True),
+ ]),
+ Question(key="features", prompt="启用功能:", multi_select=True, options=[
+ Option(label="认证", value="auth"),
+ Option(label="支付", value="payments"),
+ ]),
+])
+# answers == {"framework": "react", "features": ["auth", "payments"]}
+```
+
+## 超时
+
+两个 channel 都在构造函数接受 `default_timeout`,每个动词接受一個
+per-call 的 `timeout` kwarg(per-call 覆盖默认)。
+
+超时到期从 agent 侧的 `await` 抛出 `HitlTimedOut(BaseException)`。
+周围的工具或中间件将其转换为 `tool_result.is_error=True`,
+`details["hitl"]["decision"]="timed_out"`,模型看到干净的拒绝结果
+并能自然反应。信封的 `HitlRequest.timeout_seconds` 会自动填写,
+前端可以渲染倒计时。
+
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/reference.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/reference.md
new file mode 100644
index 0000000..20858c7
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/reference.md
@@ -0,0 +1,95 @@
+---
+title: API、事件与参考
+sidebar_position: 4
+description: "CubePi HITL 参考:Agent API、事件、追踪 span、错误参考、测试辅助与架构说明。"
+---
+
+# API、事件与参考
+
+## Agent API
+
+| 属性/方法 | 签名 | 说明 |
+|---|---|---|
+| `agent.channel` | `HitlChannel \| None` | 绑定的 channel 或 `None` |
+| `agent.in_flight_hitl_request` | `HitlRequest \| None` | channel 当前 pending(同步属性) |
+| `load_pending_hitl_request()` | `async → HitlRequest \| None` | 从 checkpointer 读取 pending(detach 后也能用) |
+| `detach()` | `async → None` | 发射 `AgentSuspendedEvent` 然后触发 `HitlDetached` |
+| `respond(*, question_id=, answer=)` | `async → None` | 恢复挂起的运行 |
+| `abort_pending(reason=)` | `async → None` | 关闭对话(两阶段:发信号 + 追加合成拒绝) |
+
+## 事件
+
+四个新事件在 agent 事件流上发射:
+
+| 事件 | 何时发射 | 关键字段 |
+|---|---|---|
+| `HitlRequestEvent` | channel 收到新的 `confirm/approve/ask` | `request: HitlRequest` |
+| `HitlAnswerEvent` | `channel.answer()` 或 `channel.cancel()` 触发 | `question_id`, `answer`, `cancelled`, `timed_out` |
+| `AgentSuspendedEvent` | `agent.detach()` 被调用时 HITL pending | `pending_request: HitlRequest` |
+| `AgentAbortedEvent` | `agent.abort_pending()` 关闭对话 | `reason: str` |
+
+## 追踪 span
+
+安装 `cubepi[tracing]` extra 后,每次 HITL await 都会包装在一个
+OpenTelemetry span 中:
+
+| Span 名称 | 属性 |
+|---|---|
+| `hitl.approve` | `hitl.tool_name`, `hitl.tool_call_id`, `hitl.outcome`, `hitl.from_resume`, `hitl.duration_seconds` |
+| `hitl.confirm` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
+| `hitl.ask` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
+
+`hitl.outcome` 可以是:`approved`, `denied`, `edited`, `answered`,
+`cancelled`, `timed_out`, `aborted`, `detached`。
+
+追踪导入是懒式的 —— 未安装 `opentelemetry` 时,channel 静默回退到
+无操作 span。
+
+## 错误参考
+
+| 异常 | 基类 | 含义 |
+|---|---|---|
+| `HitlCancelled(reason)` | `BaseException` | 宿主调了 `channel.cancel(qid)` |
+| `HitlTimedOut(seconds)` | `BaseException` | per-call 或 channel 默认超时到期 |
+| `HitlDetached` | `BaseException` | HITL await 期间调了 `agent.detach()` |
+| `HitlAborted` | `BaseException` | `agent.abort_pending()` 向 agent 发信号 |
+| `HitlConcurrencyError` | `Exception` | channel 已有 pending 时再次调用 `confirm/approve/ask` |
+| `HitlStaleAnswer` | `Exception` | `channel.answer(qid)` 的 qid 与当前 pending 不匹配 |
+| `HitlNoPendingRequest` | `Exception` | 调了 `agent.respond(…)` 但线程没有 `pending_request` |
+| `HitlDurabilityNotGuaranteed` | `Exception` | 自定义工具调了 `CheckpointedChannel.ask()` 但没有 `allow_inside_custom_tool=True` |
+
+`HitlControlException`(四个 `BaseException` 子类的父类)**故意**不被
+`cubepi.agent.tools._prepare_tool_call` 和 `_execute_prepared` 中现有
+的广泛 `except Exception:` 处理器捕获 —— 这模仿了 `asyncio.CancelledError`
+的模式。
+
+
+## 测试辅助
+
+```python
+from cubepi.hitl.testing import ScriptedChannel, NoopChannel
+
+# ScriptedChannel:预编程答案,按顺序消费
+ch = ScriptedChannel(answers=[
+ ApproveAnswer(decision="approve"),
+ {"color": "red"}, # ask 答案
+])
+assert len(ch.history) == 2 # 所有见过的 HitlRequest
+
+# NoopChannel:自动批准一切。用于测试中的 subagent。
+ch = NoopChannel()
+assert (await ch.approve("bash", "tc", {})).decision == "approve"
+```
+
+## 架构说明
+
+- **每线程单一 pending。** Agent 循环是顺序的——每个 `thread_id` 最多
+ 有一个 HITL 请求。并发 `confirm/approve/ask` 会抛 `HitlConcurrencyError`。
+- **Prompt-cache 前缀不变量。** 暂停与恢复之间,消息列表仅通过在末尾
+ 追加 tool-result 消息和下一条 assistant turn 来改变。不插入、重排或
+ 修改先前的消息——否则会使 provider 端的 prompt cache 失效。
+- **`question_id == tool_call_id` 适用于 approve 请求。** 无需别名或
+ 映射——已从工具流中追踪 `call_id` 的宿主可直接传递。
+- **恢复不重放。** 恢复时将答案预加载到 channel 并重新进入循环。最后一条
+ assistant message 中未决的 tool call 决定了接下来执行什么。没有基于
+ 节点的重放语义。
diff --git a/website/sidebars.ts b/website/sidebars.ts
index f1e2796..863b772 100644
--- a/website/sidebars.ts
+++ b/website/sidebars.ts
@@ -40,7 +40,12 @@ const sidebars: SidebarsConfig = {
'guides/middleware/composition',
'guides/middleware/examples',
]},
- 'guides/hitl',
+ { type: 'category', label: 'Human-in-the-Loop', items: [
+ 'guides/hitl/overview',
+ 'guides/hitl/middlewares',
+ 'guides/hitl/durable',
+ 'guides/hitl/reference',
+ ]},
{ type: 'category', label: 'MCP', items: [
'guides/mcp/loading',
'guides/mcp/auth',