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(todo): support host-validated background task waiting
xf gong932a107a9e1f
diff --git a/cubeloop/agent/agent.py b/cubeloop/agent/agent.pyindex c232349..def0ba6 100644--- a/cubeloop/agent/agent.py+++ b/cubeloop/agent/agent.py@@ -1386,8 +1386,16 @@ class Agent(Generic[TMessage]):self._state.error_message = msg.error_messageelif event.type == "agent_end":self._state.streaming_message = None++ if event.type in ("agent_end", "agent_suspended") or (+ event.type == "turn_end" and event.tool_results+ ):if self.checkpointer and self.thread_id:- await self.checkpointer.save_extra(self.thread_id, self._extra)+ try:+ await self.checkpointer.save_extra(self.thread_id, self._extra)+ except BaseException:+ self.session._mark_checkpoint_write_failure()+ raiseawait self.session._publish_agent_event(event)await self._emit_to_listeners(event)diff --git a/cubeloop/middleware/__init__.py b/cubeloop/middleware/__init__.pyindex a3e8378..a9fc6ea 100644--- a/cubeloop/middleware/__init__.py+++ b/cubeloop/middleware/__init__.py@@ -19,6 +19,9 @@ __all__ = ["TodoGuardBlocked","TodoGuardType","TodoListMiddleware",+ "TaskWaitBinding",+ "TaskWaitValidation",+ "TaskWaitValidator","TurnAction","WriteTodosInput","WRITE_TODOS_SYSTEM_PROMPT",@@ -43,6 +46,9 @@ _LAZY = {"TodoGuardBlocked": ("cubeloop.middleware.todo", "TodoGuardBlocked"),"TodoGuardType": ("cubeloop.middleware.todo", "TodoGuardType"),"TodoListMiddleware": ("cubeloop.middleware.todo", "TodoListMiddleware"),+ "TaskWaitBinding": ("cubeloop.middleware.todo", "TaskWaitBinding"),+ "TaskWaitValidation": ("cubeloop.middleware.todo", "TaskWaitValidation"),+ "TaskWaitValidator": ("cubeloop.middleware.todo", "TaskWaitValidator"),"WriteTodosInput": ("cubeloop.middleware.todo", "WriteTodosInput"),"WRITE_TODOS_SYSTEM_PROMPT": ("cubeloop.middleware.todo",diff --git a/cubeloop/middleware/todo.py b/cubeloop/middleware/todo.pyindex af6701d..cad0c21 100644--- a/cubeloop/middleware/todo.py+++ b/cubeloop/middleware/todo.py@@ -24,8 +24,10 @@ AssistantMessage / ToolResultMessage types directly.from __future__ import annotationsimport asyncio+import copy+import hashlibimport json-from collections.abc import Callable+from collections.abc import Awaitable, Callablefrom typing import Any, Literal, TypeAlias, castfrom typing_extensions import TypedDict@@ -36,6 +38,8 @@ from cubeloop.agent.types import (AgentContext,AgentTool,AgentToolResult,+ BeforeToolCallContext,+ BeforeToolCallResult,)from cubeloop.middleware.base import Middleware, TurnActionfrom cubeloop.providers.base import (@@ -45,9 +49,10 @@ from cubeloop.providers.base import (TextContent,ToolCall,UserMessage,+ is_synthetic_message,)-from cubeloop.types import StructuredValue-from pydantic import BaseModel+from cubeloop.types import JsonObject, StructuredValue+from pydantic import BaseModel, Field, ValidationError# ---------------------------------------------------------------------------# Tool description + system prompt (provider-neutral constants).@@ -113,6 +118,14 @@ It is important to skip using this tool when:Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfullyRemember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.""" # noqa: E501+WRITE_TODOS_TOOL_DESCRIPTION += """++If your host supports background task waiting and returns task IDs, you may include+wait_for_tasks when the remaining work depends on those tasks. Keep unfinished+todos unfinished. The host must validate the task IDs; this declaration does not+start tasks or keep this run alive. Omit it for ordinary checklist updates.+"""+WRITE_TODOS_SYSTEM_PROMPT = """## `write_todos`You have access to the `write_todos` tool to help you manage and plan complex objectives.@@ -263,6 +276,55 @@ class WriteTodosInput(BaseModel):"""Input schema for the ``write_todos`` tool."""todos: list[Todo]+ wait_for_tasks: list[str] = Field(+ default_factory=list,+ description="Background task IDs to await, only with host validation enabled.",+ )+++class TaskWaitBinding(BaseModel):+ """A successful host check bound to the checklist and committed input boundary."""++ task_ids: list[str]+ todos: list[Todo]+ run_id: str | None+ input_boundary: str+ validation: JsonObject = Field(default_factory=dict)+++class TaskWaitValidation(BaseModel):+ """Host evidence; cancelled is only meaningful for a prior successful binding."""++ status: Literal["valid", "cancelled", "invalid"]+ reason: str = ""+ validation: JsonObject = Field(default_factory=dict)+++TaskWaitValidator: TypeAlias = Callable[+ [list[str], AgentContext, TaskWaitBinding | None], Awaitable[TaskWaitValidation]+]+++def _input_boundary(ctx: AgentContext) -> str:+ inputs = [+ message+ for message in ctx.messages+ if (isinstance(message, UserMessage) and not is_synthetic_message(message))+ or isinstance(message.metadata.get("input_id"), str)+ ]+ return hashlib.sha256(+ json.dumps(+ [len(inputs), inputs[-1].model_dump(mode="json") if inputs else None],+ sort_keys=True,+ separators=(",", ":"),+ ).encode()+ ).hexdigest()+++def _clear_task_wait(extra: dict[str, Any]) -> None:+ # Save an explicit null: checkpointers may merge extra rather than replace it.+ extra["todo_task_wait"] = None+ extra["todo_task_wait_outcome"] = None# ---------------------------------------------------------------------------@@ -371,6 +433,8 @@ def _make_user_message(text: str, *, source: str) -> UserMessage:def _make_write_todos_tool(extra_ref: Callable[[], dict[str, Any]],description: str = WRITE_TODOS_TOOL_DESCRIPTION,+ prepare_wait: Callable[[str, WriteTodosInput], Awaitable[TaskWaitBinding | str]]+ | None = None,) -> AgentTool[WriteTodosInput]:"""Build the ``write_todos`` AgentTool that stores results in extra.@@ -388,7 +452,7 @@ def _make_write_todos_tool(signal: asyncio.Event | None = None,on_update: Callable[[StructuredValue], None] | None = None,) -> AgentToolResult:- del signal, on_update # unused+ del on_update # unusedtodos = args.todos# Build a dict in the format _validated_write_todos_payload expects@@ -423,10 +487,31 @@ def _make_write_todos_tool(is_error=True,)- extra_ref()["todos"] = validated_todos+ binding: TaskWaitBinding | None = None+ if args.wait_for_tasks:+ prepared = (+ await prepare_wait(tool_call_id, args)+ if prepare_wait is not None+ else "Error: Task waiting is not configured by the host."+ )+ if signal is not None and signal.is_set():+ raise asyncio.CancelledError()+ if isinstance(prepared, str):+ return AgentToolResult(+ content=[TextContent(text=prepared)], is_error=True+ )+ binding = prepared++ extra = extra_ref()+ extra["todos"] = validated_todos+ _clear_task_wait(extra)+ if binding is not None:+ extra["todo_task_wait"] = binding.model_dump(mode="json")# Build the JSON content identical to _build_todo_tool_messagepayload: dict[str, Any] = {"todos": validated_todos}+ if binding is not None:+ payload["wait_for_tasks"] = binding.task_idsif len(validated_todos) >= 3 and all(todo["status"] == "completed" for todo in validated_todos):@@ -491,6 +576,7 @@ class TodoListMiddleware(Middleware):extra_ref: Callable[[], dict[str, Any]],system_prompt: str = WRITE_TODOS_SYSTEM_PROMPT,tool_description: str = WRITE_TODOS_TOOL_DESCRIPTION,+ validate_task_wait: TaskWaitValidator | None = None,) -> None:# extra_ref must return the agent's persisted extra dict (i.e. the same# object as AgentContext.extra) so that todo state survives session@@ -499,7 +585,108 @@ class TodoListMiddleware(Middleware):self._extra_ref = extra_refself._system_prompt = system_promptself._tool_description = tool_description- self.tools = [_make_write_todos_tool(self._extra_ref, self._tool_description)]+ self._validate_task_wait = validate_task_wait+ self._tool_contexts: dict[str, AgentContext] = {}+ self.tools = [+ _make_write_todos_tool(+ self._extra_ref, self._tool_description, self._prepare_task_wait+ )+ ]++ async def before_tool_call(+ self,+ ctx: BeforeToolCallContext,+ *,+ signal: asyncio.Event | None = None,+ ) -> BeforeToolCallResult | None:+ if ctx.tool_call.name == "write_todos":+ self._tool_contexts[ctx.tool_call.id] = ctx.context+ return None++ async def _prepare_task_wait(+ self, tool_call_id: str, args: WriteTodosInput+ ) -> TaskWaitBinding | str:+ ctx = self._tool_contexts.pop(tool_call_id, None)+ if self._validate_task_wait is None:+ return "Error: Task waiting is not configured by the host."+ if ctx is None or ctx.extra is not self._extra_ref():+ return "Error: Task waiting requires the live tool context."+ ids = args.wait_for_tasks+ if any(not value.strip() for value in ids) or len(ids) != len(set(ids)):+ return "Error: wait_for_tasks must contain distinct nonempty task IDs."+ if not _unfinished_todos(args.todos):+ return "Error: Task waiting requires unfinished todo items."+ boundary, run_id = _input_boundary(ctx), ctx.run_id+ try:+ validation = await self._validate_task_wait(list(ids), ctx, None)+ if validation.status != "valid":+ return f"Error: Task wait was not validated. {validation.reason}"+ if boundary != _input_boundary(ctx) or run_id != ctx.run_id:+ return "Error: Input changed while task waiting was being validated."+ return TaskWaitBinding(+ task_ids=list(ids),+ todos=copy.deepcopy(args.todos),+ run_id=run_id,+ input_boundary=boundary,+ validation=copy.deepcopy(validation.validation),+ )+ except Exception:+ return "Error: The host could not validate task waiting."++ def _bound_task_wait(self, ctx: AgentContext) -> TaskWaitBinding | None:+ extra = self._extra_ref()+ raw = extra.get("todo_task_wait")+ if raw is None:+ return None+ try:+ binding = TaskWaitBinding.model_validate(raw)+ except ValidationError:+ _clear_task_wait(extra)+ return None+ if (+ not binding.task_ids+ or any(not task_id.strip() for task_id in binding.task_ids)+ or len(binding.task_ids) != len(set(binding.task_ids))+ or binding.run_id != ctx.run_id+ or binding.todos != extra.get("todos")+ or binding.input_boundary != _input_boundary(ctx)+ ):+ _clear_task_wait(extra)+ return None+ return binding++ async def _task_wait_allows_finalization(+ self, ctx: AgentContext, signal: asyncio.Event | None+ ) -> bool:+ binding = self._bound_task_wait(ctx)+ if binding is None or self._validate_task_wait is None:+ return False+ try:+ result = await self._validate_task_wait(+ list(binding.task_ids), ctx, binding.model_copy(deep=True)+ )+ if result.status not in ("valid", "cancelled"):+ return False+ if result.status == "cancelled" and not result.reason.strip():+ return False+ except Exception:+ return False+ finally:+ # The new host await must not convert an explicit Stop to completion.+ if signal is not None and signal.is_set():+ raise asyncio.CancelledError()+ # A callback can await while another input is committed. Recheck after it.+ if self._bound_task_wait(ctx) != binding:+ return False+ extra = self._extra_ref()+ extra["todo_task_wait_outcome"] = {+ "status": result.status,+ "reason": result.reason,+ }+ extra["todo_guard_retries"] = _reset_guard_retries()+ extra["todo_stale_iterations"] = 0+ extra["todo_finalization_correction"] = None+ return True# ------------------------------------------------------------------# transform_system_prompt@@ -581,6 +768,10 @@ class TodoListMiddleware(Middleware):# Use get (not pop) so the snapshot remains available for every# duplicate call's after_tool_call invocation.extra["todos"] = extra.get("_todos_snapshot", extra.get("todos"))+ extra["todo_task_wait"] = copy.deepcopy(extra.get("_todo_wait_snapshot"))+ extra["todo_task_wait_outcome"] = copy.deepcopy(+ extra.get("_todo_wait_outcome_snapshot")+ )return AfterToolCallResult(content=[TextContent(@@ -663,8 +854,9 @@ class TodoListMiddleware(Middleware):stale-iteration state stored in ``extra``, and returns a``TurnAction`` when the loop needs an injected nudge or hard stop."""- del signal # not usedextra = self._extra_ref()+ self._tool_contexts.clear()+ self._bound_task_wait(ctx)# We need the full message list from context to inspect the last AI msg.# In cubepi, ctx is AgentContext which has a .messages list.@@ -716,6 +908,10 @@ class TodoListMiddleware(Middleware):# decision="natural": cubepi defers inject_messages until after# ToolResultMessages, keeping Anthropic-style ordering intact.extra["_todos_snapshot"] = extra.get("todos")+ extra["_todo_wait_snapshot"] = copy.deepcopy(extra.get("todo_task_wait"))+ extra["_todo_wait_outcome_snapshot"] = copy.deepcopy(+ extra.get("todo_task_wait_outcome")+ )return TurnAction(inject_messages=cast("list[Any]", parallel_errors))validation_errors = _todo_validation_errors_local(@@ -723,6 +919,7 @@ class TodoListMiddleware(Middleware):extra.get("todos"),)if validation_errors:+ _clear_task_wait(extra)inject: list[Any] = [_make_user_message(e["error"], source="todo_validation_error")for e in validation_errors@@ -762,6 +959,8 @@ class TodoListMiddleware(Middleware):# NOTE: _guard_response reads extra["todo_guard_retries"] directly, so# we must call it BEFORE resetting retries in the clean-pass section below.if unfinished and _pure_text_assistant_response(last_assistant_msg):+ if await self._task_wait_allows_finalization(ctx, signal):+ return Nonereturn self._guard_response(extra, "finalization")# --- clean pass: commit deferred state updates ----------------------diff --git a/dev/plans/2026-09-21-todo-task-wait.md b/dev/plans/2026-09-21-todo-task-wait.mdnew file mode 100644index 0000000..455f210--- /dev/null+++ b/dev/plans/2026-09-21-todo-task-wait.md@@ -0,0 +1,12 @@+# Todo task-wait implementation++Goal: let a host-validated background wait finish the current run without falsely completing the Todo list.++1. Extend `cubeloop/middleware/todo.py` with typed validation/binding records, the optional callback, and `WriteTodosInput.wait_for_tasks`. Keep the callback optional and the existing guard as the default.+2. Use the public before-tool hook to obtain the live `AgentContext`. The tool validates before atomically updating Todo and declaration extra state; no private Agent fields or new Session lifecycle APIs. Reject a waiting tool call that lacks a matching hook context.+3. Bind to the run and current input fingerprint, including committed internal inputs. Persist only JSON-compatible data. Recheck binding and host evidence just before the pure-text unfinished guard. Cancelled is valid only with the previous successful declaration; record the reason without generating input or forcing a model turn.+4. Ensure parallel writes cannot retain one call's wait binding after checklist rollback. Normal updates clear waiting, and changed input or malformed saved bindings fail closed.+5. Add deterministic tool and real Session/checkpoint tests in `tests/middleware/test_todo_task_wait.py`. Keep `tests/test_synthetic_messages.py` and existing middleware behavior green. Update the current Todo guides and lazy exports in the same PR.+6. Persist existing Session extra in `Agent._process_event` at tool-turn end and suspension, before publishing the event. Keep normal run-end persistence. Mark a failed extra write as a checkpoint failure; cover the next-model boundary, HITL handoff, and failed writes without changing the execution lifecycle.++Verification: focused pytest while developing, then full upstream pytest, ruff, and mypy before PR; drive the upstream PR review loop. Publishing a release and switching the host dependency are separate integration steps, not implied by this module's tests passing.diff --git a/dev/specs/2026-09-21-todo-task-wait.md b/dev/specs/2026-09-21-todo-task-wait.mdnew file mode 100644index 0000000..9356ddf--- /dev/null+++ b/dev/specs/2026-09-21-todo-task-wait.md@@ -0,0 +1,21 @@+# Host-validated Todo task waiting++This is the CubeLoop portion of the approved CubePlex lifecycle design (cubeplexai/cubeplex#633, unit R). It does not add a waiting Session, keep a run alive, manage background tasks, or deliver their results.++## Contract++`write_todos` accepts an optional `wait_for_tasks` list. Ordinary calls keep their current checklist validation. A nonempty list requires an optional asynchronous host validator; without one it is rejected, not treated as permission to finish with unfinished work.++The validator receives task IDs, the live `AgentContext`, and the prior successful declaration when rechecking. It returns `valid`, `cancelled`, or `invalid`, with a reason and a JSON validation binding. The host owns task lookup, scope, permissions, result delivery readiness, and proof that a cancellation happened after the original declaration. CubeLoop imports no host model or task adapter.++A successful declaration is saved with the Todo snapshot, run ID, and input boundary in checkpointed extra state. It is installed only after both checklist and host validation succeed. An ordinary successful Todo update clears it. New input, including the initial message of a new run, or a different Todo snapshot invalidates it. Framework reminder messages alone do not invalidate the boundary. If context compaction cannot preserve the boundary, fail closed and require a new declaration.++Extra must be saved at completed tool-turn boundaries before the next model call, and before publishing a durable HITL suspension, not only at normal run end. Otherwise a crash or HITL handoff loses a successfully validated declaration. This uses the existing checkpoint extra API and does not add a Session lifecycle state. A failed write marks the checkpoint inconsistent and must not publish a successful suspension or completion.++Before the existing unfinished-Todo pure-text guard forces another model call, revalidate the declaration. `valid` allows natural completion while leaving unfinished items unchanged. `cancelled` does the same only for an existing, still-bound successful declaration, and stores the user's cancellation reason. It never permits creation of a new declaration. Invalid IDs, missing authority, validation failures, changed input, or an unconfigured validator retain the normal guard.++This exemption cannot bypass malformed Todo input, parallel write restrictions, explicit stop, HITL, or another middleware's stop decision. It emits no notification, starts no run, and does not modify historical messages or a dynamic system prompt prefix.++## Evidence required++Tests use the real tool/middleware/Session path with FauxProvider and checkpoint storage: valid natural completion, unchanged unconfigured behavior, invalid/cancelled first declarations, callback failure, checkpoint restore, input-boundary invalidation, ordinary updates, parallel writes, and cancellation at finalization. Both English and current Chinese Todo docs describe the optional host contract.diff --git a/tests/middleware/test_init_exports.py b/tests/middleware/test_init_exports.pyindex eba9034..956ad35 100644--- a/tests/middleware/test_init_exports.py+++ b/tests/middleware/test_init_exports.py@@ -11,6 +11,8 @@ def test_lazy_exports_resolve_builtin_middleware() -> None:assert middleware.SubagentMiddleware.__name__ == "SubagentMiddleware"assert middleware.SubagentSpec.__name__ == "SubagentSpec"assert middleware.ToolResultLimitMiddleware.__name__ == "ToolResultLimitMiddleware"+ assert middleware.TaskWaitBinding.__name__ == "TaskWaitBinding"+ assert middleware.TaskWaitValidation.__name__ == "TaskWaitValidation"def test_unknown_lazy_export_raises_attribute_error() -> None:diff --git a/tests/middleware/test_todo_task_wait.py b/tests/middleware/test_todo_task_wait.pynew file mode 100644index 0000000..b2ef680--- /dev/null+++ b/tests/middleware/test_todo_task_wait.py@@ -0,0 +1,562 @@+from __future__ import annotations++import asyncio+import json+from typing import Any++import pytest++from cubeloop import Agent+from cubeloop.agent.types import AgentContext+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl.ask_user import ask_user_tool+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.middleware.base import Middleware, TurnAction+from cubeloop.middleware.todo import (+ TaskWaitBinding,+ TaskWaitValidation,+ TaskWaitValidator,+ TodoListMiddleware,+)+from cubeloop.providers.base import (+ AssistantMessage,+ TextContent,+ ToolCall,+ ToolResultMessage,+ UserMessage,+ synthetic_user_message,+)+from cubeloop.providers.faux import FauxProvider, faux_assistant_message, faux_tool_call+from cubeloop.session import InputEnvelope, PromptExecutionRequest++TODOS = [{"content": "Wait for build result", "status": "in_progress"}]+++def waiting_call(*, tasks: list[str] | None = None) -> AssistantMessage:+ return faux_assistant_message(+ faux_tool_call(+ "write_todos",+ {+ "todos": TODOS,+ "wait_for_tasks": tasks if tasks is not None else ["task-a"],+ },+ )+ )+++def agent_with_wait(+ validator: TaskWaitValidator | None,+ *,+ responses: list[Any] | None = None,+ checkpointer: MemoryCheckpointer | None = None,+) -> tuple[Agent, MemoryCheckpointer]:+ provider = FauxProvider(provider_id="faux")+ provider.set_responses(+ responses+ or [+ waiting_call(),+ faux_assistant_message("The build is running; I will report its result."),+ faux_assistant_message(+ faux_tool_call(+ "write_todos",+ {+ "todos": [+ {"content": "Wait for build result", "status": "completed"}+ ]+ },+ )+ ),+ faux_assistant_message("Forced correction."),+ ]+ )+ storage = checkpointer or MemoryCheckpointer()+ middleware = TodoListMiddleware(+ extra_ref=lambda: agent.session.state_context,+ validate_task_wait=validator,+ )+ agent = Agent(+ model=provider.model("faux"),+ middleware=[middleware],+ checkpointer=storage,+ thread_id="task-wait",+ )+ return agent, storage+++async def execute(agent: Agent, *, run_id: str = "run-a") -> None:+ result = await agent.session.execute(+ PromptExecutionRequest(+ run_id=run_id, attempt_id=f"{run_id}-attempt", message="build"+ )+ )+ assert result.outcome == "completed", result+ assert result.checkpoint_committed+++async def test_valid_wait_finishes_without_faking_todo_completion() -> None:+ calls: list[TaskWaitBinding | None] = []++ async def validate(+ ids: list[str], ctx: AgentContext, prior: TaskWaitBinding | None+ ) -> TaskWaitValidation:+ assert ids == ["task-a"] and ctx.run_id == "run-a"+ calls.append(prior)+ return TaskWaitValidation(status="valid", validation={"generation": 7})++ agent, storage = agent_with_wait(validate)+ await execute(agent)+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None+ assert checkpoint.extra["todos"] == TODOS+ assert len([m for m in checkpoint.messages if isinstance(m, AssistantMessage)]) == 2+ assert len(calls) == 2 and calls[0] is None and calls[1] is not None+ assert calls[1].validation == {"generation": 7}++[email protected]("outcome", ["unconfigured", "invalid", "cancelled", "failure"])+async def test_new_declaration_requires_positive_host_validation(outcome: str) -> None:+ async def validate(+ ids: list[str], ctx: AgentContext, prior: TaskWaitBinding | None+ ) -> TaskWaitValidation:+ if outcome == "failure":+ raise RuntimeError("authority lookup unavailable")+ return TaskWaitValidation(+ status="cancelled" if outcome == "cancelled" else "invalid",+ reason="not authorized",+ )++ agent, storage = agent_with_wait(None if outcome == "unconfigured" else validate)+ await execute(agent)+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None+ result = next(m for m in checkpoint.messages if isinstance(m, ToolResultMessage))+ assert result.is_error+ assert checkpoint.extra.get("todo_task_wait") is None+++async def test_later_user_cancellation_finishes_without_another_model_call() -> None:+ async def validate(+ ids: list[str], ctx: AgentContext, prior: TaskWaitBinding | None+ ) -> TaskWaitValidation:+ if prior is None:+ return TaskWaitValidation(status="valid", validation={"accepted_at": 10})+ assert prior.validation == {"accepted_at": 10}+ return TaskWaitValidation(status="cancelled", reason="user stopped the task")++ agent, storage = agent_with_wait(validate)+ await execute(agent)+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None+ assert checkpoint.extra["todos"] == TODOS+ assert checkpoint.extra["todo_task_wait_outcome"] == {+ "status": "cancelled",+ "reason": "user stopped the task",+ }+ assert len([m for m in checkpoint.messages if isinstance(m, AssistantMessage)]) == 2+++async def valid(+ ids: list[str], ctx: AgentContext, prior: TaskWaitBinding | None+) -> TaskWaitValidation:+ return TaskWaitValidation(status="valid", validation={"accepted": True})+++def complete_call() -> AssistantMessage:+ return faux_assistant_message(+ faux_tool_call(+ "write_todos",+ {"todos": [{"content": "Wait for build result", "status": "completed"}]},+ )+ )+++async def test_checkpoint_restore_new_initial_input_invalidates_old_wait() -> None:+ first, storage = agent_with_wait(valid)+ await execute(first)+ first_checkpoint = await storage.load("task-wait")+ assert first_checkpoint is not None and first_checkpoint.extra["todo_task_wait"]+ second, _ = agent_with_wait(+ valid,+ checkpointer=storage,+ responses=[+ faux_assistant_message("New request needs work."),+ complete_call(),+ faux_assistant_message("Finished new request."),+ ],+ )+ await second.session.load_checkpoint()+ await execute(second, run_id="run-b")+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None+ assert checkpoint.extra["todo_task_wait"] is None+ assert any(+ message.run_id == "run-b"+ and message.metadata.get("synthetic_source") == "todo_guard"+ for message in checkpoint.messages+ )+++async def test_successful_update_without_wait_clears_previous_declaration() -> None:+ agent, storage = agent_with_wait(+ valid,+ responses=[+ waiting_call(),+ faux_assistant_message(faux_tool_call("write_todos", {"todos": TODOS})),+ faux_assistant_message("Not a waiting declaration anymore."),+ complete_call(),+ faux_assistant_message("Done."),+ ],+ )+ await execute(agent)+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None and checkpoint.extra["todo_task_wait"] is None+ assert any(+ m.metadata.get("synthetic_source") == "todo_guard" for m in checkpoint.messages+ )++[email protected]("kind", ["user", "background"])+async def test_committed_live_input_invalidates_wait(kind: str) -> None:+ import asyncio++ entered, release = asyncio.Event(), asyncio.Event()++ async def waiting_response(messages: Any, model: Any) -> AssistantMessage:+ entered.set()+ await release.wait()+ return faux_assistant_message("Waiting for the background result.")++ agent, storage = agent_with_wait(+ valid,+ responses=[+ waiting_call(),+ waiting_response,+ faux_assistant_message("Handle the new input."),+ complete_call(),+ faux_assistant_message("Done."),+ ],+ )+ running = asyncio.create_task(execute(agent))+ try:+ await asyncio.wait_for(entered.wait(), timeout=2)+ message = (+ UserMessage(content=[TextContent(text="new instruction")])+ if kind == "user"+ else synthetic_user_message("task-a finished", source="background_task")+ )+ receipt = agent.session.submit_input(+ InputEnvelope(input_id="new-input", message=message, mode="steer")+ )+ assert receipt.status == "queued"+ finally:+ release.set()+ await running+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None+ assert checkpoint.extra["todo_task_wait"] is None+ assert any(m.metadata.get("input_id") == "new-input" for m in checkpoint.messages)+ assert any(+ m.metadata.get("synthetic_source") == "todo_guard" for m in checkpoint.messages+ )++[email protected]("outcome", ["invalid", "failure", "cancelled_without_reason"])+async def test_failed_revalidation_retains_normal_finalization_guard(+ outcome: str,+) -> None:+ async def validate(+ ids: list[str], ctx: AgentContext, prior: TaskWaitBinding | None+ ) -> TaskWaitValidation:+ if prior is None:+ return TaskWaitValidation(status="valid")+ if outcome == "failure":+ raise RuntimeError("lookup failed")+ return TaskWaitValidation(+ status="cancelled" if outcome == "cancelled_without_reason" else "invalid"+ )++ agent, storage = agent_with_wait(validate)+ await execute(agent)+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None+ assert len([m for m in checkpoint.messages if isinstance(m, AssistantMessage)]) == 4+ assert any(+ m.metadata.get("synthetic_source") == "todo_guard" for m in checkpoint.messages+ )+++async def test_parallel_updates_restore_wait_and_todos_together() -> None:+ agent, storage = agent_with_wait(+ valid,+ responses=[+ waiting_call(),+ faux_assistant_message(+ [+ faux_tool_call(+ "write_todos", {"todos": TODOS, "wait_for_tasks": ["task-b"]}+ ),+ faux_tool_call("write_todos", {"todos": TODOS}),+ ]+ ),+ faux_assistant_message("The original background task is still running."),+ ],+ )+ await execute(agent)+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None and checkpoint.extra["todos"] == TODOS+ assert checkpoint.extra["todo_task_wait"]["task_ids"] == ["task-a"]+ results = [m for m in checkpoint.messages if isinstance(m, ToolResultMessage)]+ assert not results[0].is_error and all(m.is_error for m in results[1:])+++async def test_new_input_during_initial_validation_cannot_get_old_authorization() -> (+ None+):+ async def validate(+ ids: list[str], ctx: AgentContext, prior: TaskWaitBinding | None+ ) -> TaskWaitValidation:+ ctx.messages.append(UserMessage(content=[TextContent(text="new request")]))+ return TaskWaitValidation(status="valid")++ agent, storage = agent_with_wait(validate)+ await execute(agent)+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None+ first_result = next(+ m for m in checkpoint.messages if isinstance(m, ToolResultMessage)+ )+ assert first_result.is_error+++async def test_binding_survives_json_checkpoint_restore_at_same_input_boundary() -> (+ None+):+ agent, storage = agent_with_wait(valid)+ await execute(agent)+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None+ extra = json.loads(json.dumps(checkpoint.extra))+ restored = TodoListMiddleware(extra_ref=lambda: extra, validate_task_wait=valid)+ ctx = AgentContext(+ system_prompt="", messages=checkpoint.messages, extra=extra, run_id="run-a"+ )+ assert (+ await restored.after_model_response(+ faux_assistant_message("Still waiting."), ctx+ )+ is None+ )+ assert extra["todos"] == TODOS and extra["todo_task_wait"]["task_ids"] == ["task-a"]+++async def test_other_middleware_can_still_require_another_turn() -> None:+ class OneMoreTurn(Middleware):+ requested = False++ async def after_model_response(self, response, ctx, *, signal=None):+ if self.requested or any(isinstance(c, ToolCall) for c in response.content):+ return None+ self.requested = True+ return TurnAction(decision="loop_to_model")++ provider = FauxProvider(provider_id="faux")+ provider.set_responses(+ [+ waiting_call(),+ faux_assistant_message("First reply."),+ faux_assistant_message("Second."),+ ]+ )+ storage = MemoryCheckpointer()+ todo = TodoListMiddleware(+ extra_ref=lambda: agent.session.state_context, validate_task_wait=valid+ )+ agent = Agent(+ model=provider.model("faux"),+ middleware=[OneMoreTurn(), todo],+ checkpointer=storage,+ thread_id="task-wait",+ )+ await execute(agent)+ assert provider.call_count == 3+ assert agent.session.state_context["todos"] == TODOS++[email protected]("phase", ["initial", "recheck"])+async def test_explicit_stop_during_wait_validation_is_still_cancelled(+ phase: str,+) -> None:+ entered, release = asyncio.Event(), asyncio.Event()++ async def validate(+ ids: list[str], ctx: AgentContext, prior: TaskWaitBinding | None+ ) -> TaskWaitValidation:+ if (prior is None) == (phase == "initial"):+ entered.set()+ await release.wait()+ return TaskWaitValidation(status="valid")++ agent, _ = agent_with_wait(validate)+ running = asyncio.create_task(+ agent.session.execute(+ PromptExecutionRequest(+ run_id="run-a", attempt_id="attempt-a", message="build"+ )+ )+ )+ try:+ await asyncio.wait_for(entered.wait(), timeout=2)+ agent.session.request_cancel()+ finally:+ release.set()+ result = await running+ assert result.outcome == "cancelled"+ if phase == "initial":+ assert agent.session.state_context.get("todo_task_wait") is None+ else:+ assert agent.session.state_context["todos"] == TODOS+ assert agent.session.state_context.get("todo_task_wait_outcome") is None+++async def test_invalid_todo_payload_does_not_get_wait_exemption() -> None:+ called = False++ async def validate(+ ids: list[str], ctx: AgentContext, prior: TaskWaitBinding | None+ ) -> TaskWaitValidation:+ nonlocal called+ called = True+ return TaskWaitValidation(status="valid")++ agent, storage = agent_with_wait(+ validate,+ responses=[+ faux_assistant_message(+ faux_tool_call(+ "write_todos",+ {+ "todos": [{"content": "", "status": "in_progress"}],+ "wait_for_tasks": ["task-a"],+ },+ )+ ),+ faux_assistant_message("Invalid checklist rejected."),+ ],+ )+ await execute(agent)+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None and not called+ result = next(m for m in checkpoint.messages if isinstance(m, ToolResultMessage))+ assert result.is_error and checkpoint.extra.get("todo_task_wait") is None+++async def test_wait_state_does_not_change_system_prompt_prefix() -> None:+ extra: dict[str, Any] = {}+ mw = TodoListMiddleware(extra_ref=lambda: extra, validate_task_wait=valid)+ ctx = AgentContext(system_prompt="base", messages=[], extra=extra)+ before = await mw.transform_system_prompt("base", ctx=ctx)+ extra.update(+ {+ "todos": TODOS,+ "todo_task_wait_outcome": {"status": "cancelled", "reason": "Stop"},+ }+ )+ assert await mw.transform_system_prompt("base", ctx=ctx) == before++[email protected]("same_turn", [False, True])+async def test_valid_task_wait_does_not_complete_a_pending_hitl_request(+ same_turn: bool,+) -> None:+ storage = MemoryCheckpointer()+ channel = CheckpointedChannel(+ checkpointer=storage, thread_id="task-wait", run_id="run-a"+ )+ provider = FauxProvider(provider_id="faux")+ ask = faux_tool_call(+ "ask_user", {"questions": [{"key": "continue", "prompt": "Continue?"}]}+ )+ provider.set_responses(+ [faux_assistant_message([*waiting_call().content, ask])]+ if same_turn+ else [waiting_call(), faux_assistant_message(ask)]+ )+ todo = TodoListMiddleware(+ extra_ref=lambda: agent.session.state_context, validate_task_wait=valid+ )+ agent = Agent(+ model=provider.model("faux"),+ tools=[ask_user_tool(channel)],+ middleware=[todo],+ checkpointer=storage,+ channel=channel,+ thread_id="task-wait",+ )+ pending = asyncio.Event()+ agent.session.subscribe(+ lambda envelope: (+ pending.set() if envelope.event.type == "hitl_request" else None+ )+ )+ running = asyncio.create_task(+ agent.session.execute(+ PromptExecutionRequest(+ run_id="run-a", attempt_id="attempt-a", message="build"+ )+ )+ )+ try:+ await asyncio.wait_for(pending.wait(), timeout=2)+ assert channel.pending is not None and not running.done()+ await agent.session.request_detach()+ result = await running+ finally:+ if not running.done():+ running.cancel()+ await running+ assert result.outcome == "suspended" and result.pending_request is not None+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None and checkpoint.extra["todos"] == TODOS+ assert checkpoint.extra["todo_task_wait_outcome"] is None+ assert await storage.load_pending("task-wait") is not None+++async def test_wait_binding_is_checkpointed_before_the_next_model_call() -> None:+ storage = MemoryCheckpointer()++ async def check_durable_binding(messages, model):+ checkpoint = await storage.load("task-wait")+ assert checkpoint is not None+ assert checkpoint.extra["todos"] == TODOS+ assert checkpoint.extra["todo_task_wait"]["task_ids"] == ["task-a"]+ return faux_assistant_message("Waiting for the build.")++ agent, _ = agent_with_wait(+ valid, checkpointer=storage, responses=[waiting_call(), check_durable_binding]+ )+ await execute(agent)+++async def test_wait_checkpoint_failure_cannot_report_success_or_continue() -> None:+ class FailingExtraCheckpointer(MemoryCheckpointer):+ async def save_extra(self, thread_id, extra):+ if extra.get("todo_task_wait"):+ raise OSError("checkpoint unavailable")+ await super().save_extra(thread_id, extra)++ storage = FailingExtraCheckpointer()+ advanced = False++ async def must_not_advance(messages, model):+ nonlocal advanced+ advanced = True+ return faux_assistant_message("Waiting.")++ agent, _ = agent_with_wait(+ valid, checkpointer=storage, responses=[waiting_call(), must_not_advance]+ )+ result = await agent.session.execute(+ PromptExecutionRequest(run_id="run-a", attempt_id="attempt-a", message="build")+ )+ assert result.outcome == "failed" and not advanced+ assert not result.checkpoint_committed and not result.history_consistentdiff --git a/website/docs/guides/middleware/todo.md b/website/docs/guides/middleware/todo.mdindex 213b2aa..c0dc176 100644--- a/website/docs/guides/middleware/todo.md+++ b/website/docs/guides/middleware/todo.md@@ -23,13 +23,11 @@ through this reference so state survives checkpointing.from cubeloop import Agentfrom cubeloop.middleware import TodoListMiddleware-agent_extra: dict = {}-agent = Agent(model=provider.model("claude-sonnet-4-6"),system_prompt="You are a thorough assistant.",middleware=[- TodoListMiddleware(extra_ref=lambda: agent_extra),+ TodoListMiddleware(extra_ref=lambda: agent.session.state_context),],)```@@ -44,28 +42,23 @@ from cubeloop.middleware import TodoListMiddleware# extra_ref must return the same object as AgentContext.extra.# The helper below is the standard pattern with a checkpointed agent.-ctx_holder: dict[str, dict] = {}--def extra_ref() -> dict:- return ctx_holder.setdefault("extra", {})-agent = Agent(model=provider.model("claude-sonnet-4-6"),checkpointer=PostgresCheckpointer(...),thread_id="conv_123",middleware=[- TodoListMiddleware(extra_ref=extra_ref),+ TodoListMiddleware(extra_ref=lambda: agent.session.state_context),],)```-In practice the simplest pattern is to pass `lambda: agent.state.extra` — but-`agent.state` is only valid after the agent is constructed, so a late-binding-lambda or a shared dict reference both work.+The public `agent.session.state_context` is the live checkpoint extra mapping.+The lambda is evaluated after construction. On recovery, call+`await agent.session.load_checkpoint()` before executing a new request.## The `write_todos` tool-The tool accepts a single `todos` list. Each item has:+The tool accepts a `todos` list and optional `wait_for_tasks` task IDs. Each Todo has:- `content` — a short task description.- `status` — one of `"pending"`, `"in_progress"`, or `"completed"`.@@ -89,6 +82,61 @@ turn the run proceeds normally regardless of what the model does.This prevents the common pattern where a model completes work but forgets tomark items as done before responding.+## Waiting for host-managed background work++Pass `validate_task_wait` when your application owns background tasks that can+outlive a run. The async callback has this signature:++```python+from cubeloop.agent.types import AgentContext+from cubeloop.middleware import TaskWaitBinding, TaskWaitValidation++async def validate_task_wait(+ task_ids: list[str],+ ctx: AgentContext,+ prior: TaskWaitBinding | None,+) -> TaskWaitValidation:+ # Your service checks scope, actor permissions, cancellation, and whether+ # the tasks still have an observable result to deliver.+ return await task_service.validate_wait(task_ids, ctx, prior)++middleware = TodoListMiddleware(+ extra_ref=lambda: agent.session.state_context,+ validate_task_wait=validate_task_wait,+)+```++The host service in this example is application code, not part of CubeLoop.+It returns `TaskWaitValidation(status="valid", validation={...})` only after+checking the tasks. Store only JSON-compatible, non-secret evidence in+`validation`; it is checkpointed and returned in the next `prior` binding.+No validator means a nonempty `wait_for_tasks` is rejected.++The declaration binds task IDs to the successful Todo update, run, and current+input boundary. Before forcing a finalization correction, CubeLoop asks the+host again. A valid wait lets the run end naturally without completing unfinished+Todos or making another model call. An ordinary Todo update without task IDs+clears the declaration. New user or internal input, including a new run's initial+message, invalidates it. A changed or unprovable boundary after compaction also+requires a new declaration.++If the user cancels previously validated work, the callback may return+`status="cancelled"` with a nonempty `reason`, after proving cancellation happened+after the original validation. This also allows natural completion, preserving+the unfinished list and cancellation reason. It cannot establish a new wait.+Invalid tasks, lookup failures, or stale bindings keep the ordinary guard.+Malformed Todo updates, explicit stop, HITL, and other middleware decisions are+not bypassed.++Use a checkpointer and the live extra mapping for recoverable declarations.+Extra is saved after tool turns before another model call, before a HITL+suspension is published, and at normal run end. A failed save does not count as+a successfully checkpointed wait.+CubeLoop does not start, poll, cancel, or deliver background tasks, and does not+keep a waiting Session alive. The host remains responsible for their lifecycle+and for delivering results in a later input or run. Agents without a Todo list+do not need to call `write_todos` just to end a run.+## Stale-todo reminderIf the model makes several tool calls in a row without touching `write_todos`,@@ -125,6 +173,8 @@ All state is stored under well-known keys in `AgentContext.extra`:| `todo_guard_suppressed` | `bool` | Guard suppression flag after a blocked episode || `todo_stale_iterations` | `int` | Turns since last `write_todos` call || `todo_finalization_correction` | `bool \| None` | Whether a finalization correction was injected this turn |+| `todo_task_wait` | `dict \| None` | Validated task IDs, Todo snapshot, run/input boundary, and host evidence |+| `todo_task_wait_outcome` | `dict \| None` | Last valid/cancelled finalization decision and reason |These keys are stable across versions. Checkpointers persist them as part of`ctx.extra`, so a resumed session starts with the same checklist the model left.diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.mdindex 8e53b5c..197c0cc 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.md@@ -17,13 +17,11 @@ description: "使用 TodoListMiddleware 给 agent 添加 write_todos 工具,from cubeloop import Agentfrom cubeloop.middleware import TodoListMiddleware-agent_extra: dict = {}-agent = Agent(model=provider.model("claude-sonnet-4-6"),system_prompt="你是一个认真负责的助手。",middleware=[- TodoListMiddleware(extra_ref=lambda: agent_extra),+ TodoListMiddleware(extra_ref=lambda: agent.session.state_context),],)```@@ -35,27 +33,22 @@ from cubeloop import Agentfrom cubeloop.checkpointer import PostgresCheckpointerfrom cubeloop.middleware import TodoListMiddleware-ctx_holder: dict[str, dict] = {}--def extra_ref() -> dict:- return ctx_holder.setdefault("extra", {})-agent = Agent(model=provider.model("claude-sonnet-4-6"),checkpointer=PostgresCheckpointer(...),thread_id="conv_123",middleware=[- TodoListMiddleware(extra_ref=extra_ref),+ TodoListMiddleware(extra_ref=lambda: agent.session.state_context),],)```-最简单的写法是 `lambda: agent.state.extra`,但 `agent.state` 只在 agent-构造完成后才有效,所以延迟绑定的 lambda 或共享字典引用都可以。+公开的 `agent.session.state_context` 就是实时 checkpoint extra,lambda 在 agent+构造后才求值。恢复时,先调用 `await agent.session.load_checkpoint()`,再执行新请求。## `write_todos` 工具-该工具接受一个 `todos` 列表,每项包含:+该工具接受 `todos` 列表,以及可选的 `wait_for_tasks` 任务 ID。每个 Todo 包含:- `content` — 简短的任务描述。- `status` — `"pending"`、`"in_progress"` 或 `"completed"` 之一。@@ -74,6 +67,49 @@ agent = Agent(这防止了模型完成工作后忘记将条目标为已完成就直接回复的常见情况。+## 等待宿主管理的后台工作++应用有跨 run 后台任务时,可以给 middleware 传入异步 `validate_task_wait`:++```python+from cubeloop.agent.types import AgentContext+from cubeloop.middleware import TaskWaitBinding, TaskWaitValidation++async def validate_task_wait(+ task_ids: list[str],+ ctx: AgentContext,+ prior: TaskWaitBinding | None,+) -> TaskWaitValidation:+ return await task_service.validate_wait(task_ids, ctx, prior)++middleware = TodoListMiddleware(+ extra_ref=lambda: agent.session.state_context,+ validate_task_wait=validate_task_wait,+)+```++示例的 `task_service` 是应用自己的服务,不是 CubeLoop 内置功能。宿主负责校验当前+scope、发起者权限、取消状态,以及任务是否仍有可观察、待交付的结果。成功时返回+`TaskWaitValidation(status="valid", validation={...})`;`validation` 只能包含可 JSON+序列化的非敏感证据,它会随 checkpoint 保存,并通过下次回调的 `prior` 返回。+没有配置回调时,非空 `wait_for_tasks` 会被拒绝。++成功的声明绑定任务 ID、Todo 快照、run 和当前输入边界。纯文本收尾触发未完成守卫前,+CubeLoop 再次调用宿主校验;仍有效则正常结束当前 run,不勾选未完成 Todo,也不强制+追加模型调用。不带任务 ID 的普通 Todo 更新会清除声明。新的用户或内部输入、新 run+的初始消息都会使旧声明失效;压缩上下文后无法确认原输入边界时也需重新声明。++用户后来取消已验证的工作时,宿主证明取消发生在原校验之后,可返回+`status="cancelled"` 和非空 `reason`,允许自然收尾并保留未完成列表和取消原因。+cancelled 不能用来建立新声明。无效 ID、查询失败、旧绑定仍走原有守卫;不能借等待+绕过 Todo 参数错误、显式停止、HITL 或其他 middleware 的控制。++可恢复声明需要 checkpointer 和实时 extra 引用。工具轮次结束后、下一次模型调用前,+以及发布 HITL 暂停和正常结束时都会保存 extra;保存失败不算成功持久化等待声明。+CubeLoop 不负责启动、轮询、取消或+投递后台任务,也不保持等待中的 Session;宿主负责任务生命周期及后续输入或新 run。+没有 Todo 的 agent 不需要为了结束 run 而额外调用该工具。+## 过期提醒如果模型连续多轮不调用 `write_todos`,middleware 会注入一条软性提醒,请模型同步列表。模型可以忽略该提醒,它不是硬性阻断。@@ -107,6 +143,8 @@ TodoListMiddleware(| `todo_guard_suppressed` | `bool` | 守卫阻断事件后的压制标志 || `todo_stale_iterations` | `int` | 上次调用 `write_todos` 以来的轮数 || `todo_finalization_correction` | `bool \| None` | 本轮是否注入了完成纠正消息 |+| `todo_task_wait` | `dict \| None` | 已校验任务 ID、Todo 快照、run/输入边界和宿主证据 |+| `todo_task_wait_outcome` | `dict \| None` | 最近一次 valid/cancelled 收尾判断及原因 |这些 key 跨版本保持稳定。checkpointer 将它们作为 `ctx.extra` 的一部分持久化,恢复的会话会从模型上次保留的待办列表继续。