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
chore(release): prepare 0.15.1
xf gongcdaa13345a74
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.ymlindex 46e1256..5989cdb 100644--- a/.github/workflows/docs.yml+++ b/.github/workflows/docs.yml@@ -77,11 +77,9 @@ jobs:name: website-buildpath: website/build/- name: Deploy to Cloudflare Pages- uses: cloudflare/pages-action@v1+ uses: cloudflare/wrangler-action@v4with:apiToken: ${{ secrets.CF_API_TOKEN }}accountId: ${{ secrets.CF_ACCOUNT_ID }}- projectName: cubepi- directory: website/build+ command: pages deploy website/build --project-name=cubepi --branch=main --commit-hash=${{ github.sha }}gitHubToken: ${{ secrets.GITHUB_TOKEN }}- branch: maindiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1d28645..8cb7a9a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+## [0.15.1] - 2026-09-24+### Added- **`ToolResultLimitMiddleware` caps tool-result text in `after_tool_call`.**@@ -14,7 +16,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0telling the model to narrow the call. The rewrite happens before`ToolExecutionEndEvent`, so the model, checkpointer, and host consumersall see the truncated result. Image blocks are kept; tools in- `exclude_tool_names` pass through.+ `exclude_tool_names` pass through (`#229`).+- **`TodoListMiddleware` can wait on host-validated background tasks.**+ `write_todos` accepts an optional `wait_for_tasks` list. A nonempty list+ requires `validate_task_wait`; without that callback it is rejected. A+ successful declaration is checkpointed with the Todo snapshot, run ID, and+ input boundary. Before the unfinished-Todo guard forces another model+ call, CubeLoop asks the host again. `valid`, or `cancelled` after the host+ proves the cancellation, lets the run finish with unfinished items still+ open. New input invalidates the declaration, including a new run's first+ message, a HITL answer, and human approval, denial, or editing of a tool+ call. Automatic policy approval does not. CubeLoop does not start, poll,+ cancel, or deliver the tasks (`#231`).++### Changed++- **Checkpoint `extra` is saved at more boundaries.** `save_extra` runs after+ a turn that produced tool results, when a run suspends, and at `agent_end`.+ A failed write is recorded as a checkpoint failure. The suspension or+ completion event is not published, and the run is not marked complete+ (`#231`).+- **Human approval records `hitl_trace["decision"]="human_approve"`.** The+ tool still runs with its original arguments. Policy auto-approval stays a+ silent passthrough (`#231`).++### Fixed++- **HITL answers restored through the resume slot use the same typed+ normalization as checkpoint-loaded answers**, so a restored JSON answer+ invalidates a task-wait declaration the same way a live answer does+ (`#231`).## [0.15.0] - 2026-09-16@@ -845,7 +876,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **[0.2.0]** - 2026-05-10 — see the [release notes](https://github.com/cubeplexai/cubepi/releases/tag/v0.2.0).- **[0.1.0]** - 2026-05-09 — initial release. See the [release notes](https://github.com/cubeplexai/cubepi/releases/tag/v0.1.0).-[Unreleased]: https://github.com/cubeplexai/cubeloop/compare/v0.15.0...HEAD+[Unreleased]: https://github.com/cubeplexai/cubeloop/compare/v0.15.1...HEAD+[0.15.1]: https://github.com/cubeplexai/cubeloop/compare/v0.15.0...v0.15.1[0.15.0]: https://github.com/cubeplexai/cubeloop/compare/v0.14.1...v0.15.0[0.14.1]: https://github.com/cubeplexai/cubeloop/compare/v0.13.6...v0.14.1[0.13.6]: https://github.com/cubeplexai/cubeloop/compare/v0.13.5...v0.13.6diff --git a/compat/cubepi/pyproject.toml b/compat/cubepi/pyproject.tomlindex 2c70fc3..2cad086 100644--- a/compat/cubepi/pyproject.toml+++ b/compat/cubepi/pyproject.toml@@ -1,6 +1,6 @@[project]name = "cubepi"-version = "0.15.0"+version = "0.15.1"description = "REMOVED: Install cubeloop and migrate imports from cubepi."readme = "README.md"license = "MIT"diff --git a/pyproject.toml b/pyproject.tomlindex 9b6f356..f68136d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,6 +1,6 @@[project]name = "cubeloop"-version = "0.15.0"+version = "0.15.1"description = "Pythonic async-native agent framework"readme = "README.md"license = "MIT"diff --git a/uv.lock b/uv.lockindex 396425f..27160c5 100644--- a/uv.lock+++ b/uv.lock@@ -528,7 +528,7 @@ wheels = [[[package]]name = "cubeloop"-version = "0.15.0"+version = "0.15.1"source = { editable = "." }dependencies = [{ name = "anthropic" },@@ -624,7 +624,7 @@ dev = [[[package]]name = "cubepi"-version = "0.15.0"+version = "0.15.1"source = { editable = "compat/cubepi" }[[package]]diff --git a/website/docs/guides/agents/multi-turn.md b/website/docs/guides/agents/multi-turn.mdindex cdb01cb..aa2a6f1 100644--- a/website/docs/guides/agents/multi-turn.md+++ b/website/docs/guides/agents/multi-turn.md@@ -156,7 +156,8 @@ async with SQLiteCheckpointer("conv.db") as cp:The checkpoint `extra` mapping is also restored. Middleware that wants topersist per-thread state should write into `context.extra`; the checkpointer's-`save_extra` is called at `agent_end`. Hosts should use+`save_extra` is called after a turn that produced tool results, when the run+suspends, and at `agent_end`. Hosts should use`agent.session.state_context`, which is the stable live mapping, and`await agent.session.load_checkpoint()` when they need an explicit idle-timerestore. Messages and extra are installed together, including checkpointsdiff --git a/website/docs/guides/checkpointing/custom.md b/website/docs/guides/checkpointing/custom.mdindex 69a98c9..eaf5e11 100644--- a/website/docs/guides/checkpointing/custom.md+++ b/website/docs/guides/checkpointing/custom.md@@ -30,7 +30,7 @@ in-memory dict — anything that can append-and-list.|---|---|| `load(thread_id)` | Once, on the first `prompt()` after agent construction || `append(thread_id, messages)` | Inside `message_end`, every time a message is finalised |-| `save_extra(thread_id, extra)` | At `agent_end`, with the current `_extra` dict |+| `save_extra(thread_id, extra)` | After a turn that produced tool results, on `agent_suspended`, and at `agent_end`, with the current `_extra` dict |`load` returns `None` for unknown threads. `append` and `save_extra`do nothing useful if you don't already have a thread; create the rowdiff --git a/website/docs/guides/checkpointing/sqlite.md b/website/docs/guides/checkpointing/sqlite.mdindex 5d8b024..78873f8 100644--- a/website/docs/guides/checkpointing/sqlite.md+++ b/website/docs/guides/checkpointing/sqlite.md@@ -76,9 +76,10 @@ CREATE TABLE thread_extra (- Every `UserMessage`, `AssistantMessage`, and `ToolResultMessage`becomes one row in `messages`. Pydantic `model_dump()` is used forthe JSON payload.-- The `extra` dict on `AgentContext` is persisted on `agent_end` into- `thread_extra`. Middleware that wants thread-scoped state should- write into `context.extra`.+- The `extra` dict on `AgentContext` is persisted into `thread_extra`+ after a turn that produced tool results, on HITL suspension+ (`agent_suspended`), and at `agent_end`. Middleware that wants+ thread-scoped state should write into `context.extra`.This schema is append-only. CubeLoop never updates or deletes rows.diff --git a/website/docs/guides/middleware/compaction.md b/website/docs/guides/middleware/compaction.mdindex 8bcf146..06a47a6 100644--- a/website/docs/guides/middleware/compaction.md+++ b/website/docs/guides/middleware/compaction.md@@ -48,7 +48,7 @@ The middleware writes two keys into `AgentContext.extra`:- `compaction` — the summary state and the message refs it covers.- `compaction_until_msg_index` — the history boundary summarized so far.-When a checkpointer is attached, CubeLoop saves `ctx.extra` at `agent_end`, so the+When a checkpointer is attached, CubeLoop saves `ctx.extra` after a turn that produced tool results, on HITL suspension, and at `agent_end`, so thenext process can resume with the existing summary. If the message refs no longermatch the current history, the middleware clears the stale state and starts overrather than sending an invalid summary.diff --git a/website/docs/guides/middleware/examples.md b/website/docs/guides/middleware/examples.mdindex 6ca00ba..9a76835 100644--- a/website/docs/guides/middleware/examples.md+++ b/website/docs/guides/middleware/examples.md@@ -136,7 +136,7 @@ class ToolLoggingMiddleware(Middleware):it's:- Visible to other middleware via the same `ctx.context`.-- Persisted by checkpointers via `save_extra` at `agent_end`.+- Persisted by checkpointers via `save_extra` after tool-result turns, on suspension, and at `agent_end`.- Reset when a new conversation starts (a new `thread_id`).## Sliding-window truncationdiff --git a/website/docs/recipes/sandbox-confirm.md b/website/docs/recipes/sandbox-confirm.mdindex 3736dce..310d03e 100644--- a/website/docs/recipes/sandbox-confirm.md+++ b/website/docs/recipes/sandbox-confirm.md@@ -111,7 +111,7 @@ async def host_loop(channel: CheckpointedChannel):| Human chose | Tool outcome | `hitl_trace["decision"]` | Model sees ||---|---|---|---|-| Approve | Runs with original args | unset (passthrough, no HITL details) | Normal `tool_result` |+| Approve | Runs with original args | `"human_approve"` | Normal `tool_result` || Deny | Blocked | `"human_deny"` | `tool_result.is_error=True` with user's reason || Edit | Runs with edited args | `"edit"` + `original_args` / `edited_args` | Normal `tool_result` (from the edited execution) |diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/multi-turn.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/multi-turn.mdindex e143c5a..40f26b5 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/multi-turn.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/multi-turn.md@@ -127,7 +127,7 @@ async with SQLiteCheckpointer("conv.db") as cp:checkpoint 中的 `extra` 映射也会被恢复。希望持久化 per-thread 状态的middleware 应将数据写入 `context.extra`;checkpointer 的 `save_extra` 会在-`agent_end` 时被调用。宿主应通过 `agent.session.state_context` 访问这个引用稳定的+产生工具结果的轮次结束之后、运行暂停时,以及 `agent_end` 时被调用。宿主应通过 `agent.session.state_context` 访问这个引用稳定的实时映射;需要在空闲时显式恢复状态,则调用`await agent.session.load_checkpoint()`。消息和 extra 会一起安装,即使 checkpoint中的消息列表为空也一样。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/custom.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/custom.mdindex 467011f..192921b 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/custom.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/custom.md@@ -28,7 +28,7 @@ HITL 生命周期方法;宿主使用相应功能时也需要实现这些方法|---|---|| `load(thread_id)` | agent 构造后第一次调用 `prompt()` 时,调用一次 || `append(thread_id, messages)` | 在 `message_end` 内,每次消息完成时调用 |-| `save_extra(thread_id, extra)` | 在 `agent_end` 时,携带当前的 `_extra` 字典调用 |+| `save_extra(thread_id, extra)` | 产生工具结果的轮次结束之后、`agent_suspended` 时,以及 `agent_end` 时,携带当前的 `_extra` 字典调用 |对未知的 thread,`load` 返回 `None`。若还没有该 thread,`append` 和 `save_extra` 不会做任何有意义的事;请在第一次调用时创建对应的记录行。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.mdindex 6990932..abc7704 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.md@@ -72,7 +72,7 @@ CREATE TABLE thread_extra (- 每条 `UserMessage`、`AssistantMessage`、`ToolResultMessage` 各占`messages` 一行。JSON payload 通过 Pydantic `model_dump()` 生成。-- `AgentContext` 的 `extra` dict 在 `agent_end` 时持久化到 `thread_extra`。+- `AgentContext` 的 `extra` dict 会在产生工具结果的轮次结束之后、HITL 暂停(`agent_suspended`)时,以及 `agent_end` 时写入 `thread_extra`。Middleware 需要持久化线程级状态时,往 `context.extra` 写。这个 schema 是追加式的。CubeLoop 从不 update 或 delete 行。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/compaction.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/compaction.mdindex 2f1a410..ebf6919 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/compaction.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/compaction.md@@ -44,7 +44,7 @@ middleware 会向 `AgentContext.extra` 写入两个键:- `compaction` —— 摘要状态,以及它覆盖的消息引用。- `compaction_until_msg_index` —— 已总结到的历史边界。-绑定 checkpointer 时,CubeLoop 会在 `agent_end` 通过 `save_extra` 保存+绑定 checkpointer 时,CubeLoop 会在产生工具结果的轮次结束之后、HITL 暂停时,以及 `agent_end` 时通过 `save_extra` 保存`ctx.extra`,所以下一个进程可以带着已有摘要继续。如果消息引用与当前历史不再匹配,middleware 会清除旧状态并重新开始,而不是发送无效摘要。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/examples.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/examples.mdindex 4dd0f95..a333ccb 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/examples.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/examples.md@@ -130,7 +130,7 @@ class ToolLoggingMiddleware(Middleware):`ctx.context.extra` 是存储每次运行状态的最佳位置,因为:- 其他中间件可通过同一个 `ctx.context` 看到。-- Checkpointer 在 `agent_end` 时通过 `save_extra` 持久化。+- Checkpointer 在产生工具结果的轮次结束之后、运行暂停时,以及 `agent_end` 时通过 `save_extra` 持久化。- 新对话开始时(新的 `thread_id`)会自动重置。## 滑动窗口截断 {#sliding-window-truncation}@@ -163,6 +163,23 @@ class SummaryInjector(Middleware):return f"{system_prompt}\n\nContext: {summary}".strip()```+## 内置工具结果长度限制++`ToolResultLimitMiddleware` 在 `after_tool_call` 里截断过长的工具结果文本,避免一次 `execute`、抓取或 MCP 调用的输出撑破下一次模型请求,或超出宿主的事件大小限制。++```python+from cubeloop.middleware import ToolResultLimitMiddleware++agent = Agent(+ model=…,+ middleware=[+ ToolResultLimitMiddleware(max_chars=20_000),+ ],+)+```++选项、排除名单和放置顺序见[工具结果长度限制](./tool-result-limit.md)。+## 最大轮次 / 预算上限在达到最大轮次数或成本上限时硬停止 agent:diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/tool-result-limit.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/tool-result-limit.mdnew file mode 100644index 0000000..f2842cf--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/tool-result-limit.md@@ -0,0 +1,52 @@+---+title: 工具结果长度限制+description: "用 ToolResultLimitMiddleware 在 ToolExecutionEndEvent 发出前截断过长的工具结果文本。"+---++# 工具结果长度限制++`ToolResultLimitMiddleware` 在 `after_tool_call` 里截断过长的工具结果文本,发生在 CubeLoop 发布 `ToolExecutionEndEvent` 之前。模型、checkpointer 和宿主的事件消费者看到的都是截断后的结果。++工具可能返回不受控的输出时使用它,比如 shell、网页抓取、MCP 工具。过大的结果会撑破上下文窗口,或者超出宿主的事件大小限制。++## 基本设置++```python+from cubeloop import Agent+from cubeloop.middleware import ToolResultLimitMiddleware++agent = Agent(+ model=provider.model("claude-sonnet-4-6"),+ middleware=[+ ToolResultLimitMiddleware(),+ ],+)+```++默认上限是 20,000 个字符的文本内容。不超过上限的结果原样通过(`after_tool_call` 返回 `None`)。超过上限时,文本保留前 `max_chars` 个字符,并附上提示:++```text+[truncated: tool result was 1082017 characters; showing first 20000. Narrow the tool call and retry.]+```++图片块会保留。只有 `TextContent` 计入上限。++## 选项++```python+ToolResultLimitMiddleware(+ max_chars=20_000,+ exclude_tool_names={"load_skill"},+)+```++- `max_chars`:从原始结果保留的最大文本字符数,必须 `>= 1`。+- `exclude_tool_names`:跳过截断的工具名。完整内容本身就是负载时使用,例如 `load_skill` 返回的 skill 正文。++## 放置顺序++把它放在其他 `after_tool_call` middleware **之后**,让它们先改写完整结果,再由截断后的文本进入 `ToolExecutionEndEvent`。++CubeLoop 默认的组合规则是最后一个非 `None` 返回值生效。排在后面的 middleware 如果返回了不含 `content` 的 `AfterToolCallResult`,这次改写会被丢掉。把 `ToolResultLimitMiddleware` 放在最后,或者换一个会合并 `content` 和 `details` 的 composer。++子 agent 不会继承父 agent 的 middleware。如果子工具的结果也要限制,通过 `SubagentMiddleware(inherited_middleware=...)` 传入同一个实例或再创建一个。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/sandbox-confirm.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/sandbox-confirm.mdindex decaeb9..90e1051 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/sandbox-confirm.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/sandbox-confirm.md@@ -110,7 +110,7 @@ async def host_loop(channel: CheckpointedChannel):| 人类选择 | 工具结果 | `hitl_trace["decision"]` | 模型看到 ||---|---|---|---|-| 批准 | 使用原始参数执行 | 未设置(直通,无 HITL 细节) | 正常 `tool_result` |+| 批准 | 使用原始参数执行 | `"human_approve"` | 正常 `tool_result` || 拒绝 | 被阻止 | `"human_deny"` | `tool_result.is_error=True` 及用户的原因 || 编辑 | 使用编辑后的参数执行 | `"edit"` + `original_args` / `edited_args` | 正常 `tool_result`(来自编辑后的执行) |diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/agents/multi-turn.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/agents/multi-turn.mdindex e143c5a..40f26b5 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/agents/multi-turn.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/agents/multi-turn.md@@ -127,7 +127,7 @@ async with SQLiteCheckpointer("conv.db") as cp:checkpoint 中的 `extra` 映射也会被恢复。希望持久化 per-thread 状态的middleware 应将数据写入 `context.extra`;checkpointer 的 `save_extra` 会在-`agent_end` 时被调用。宿主应通过 `agent.session.state_context` 访问这个引用稳定的+产生工具结果的轮次结束之后、运行暂停时,以及 `agent_end` 时被调用。宿主应通过 `agent.session.state_context` 访问这个引用稳定的实时映射;需要在空闲时显式恢复状态,则调用`await agent.session.load_checkpoint()`。消息和 extra 会一起安装,即使 checkpoint中的消息列表为空也一样。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/checkpointing/custom.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/checkpointing/custom.mdindex 467011f..192921b 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/checkpointing/custom.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/checkpointing/custom.md@@ -28,7 +28,7 @@ HITL 生命周期方法;宿主使用相应功能时也需要实现这些方法|---|---|| `load(thread_id)` | agent 构造后第一次调用 `prompt()` 时,调用一次 || `append(thread_id, messages)` | 在 `message_end` 内,每次消息完成时调用 |-| `save_extra(thread_id, extra)` | 在 `agent_end` 时,携带当前的 `_extra` 字典调用 |+| `save_extra(thread_id, extra)` | 产生工具结果的轮次结束之后、`agent_suspended` 时,以及 `agent_end` 时,携带当前的 `_extra` 字典调用 |对未知的 thread,`load` 返回 `None`。若还没有该 thread,`append` 和 `save_extra` 不会做任何有意义的事;请在第一次调用时创建对应的记录行。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/checkpointing/sqlite.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/checkpointing/sqlite.mdindex 6990932..abc7704 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/checkpointing/sqlite.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/checkpointing/sqlite.md@@ -72,7 +72,7 @@ CREATE TABLE thread_extra (- 每条 `UserMessage`、`AssistantMessage`、`ToolResultMessage` 各占`messages` 一行。JSON payload 通过 Pydantic `model_dump()` 生成。-- `AgentContext` 的 `extra` dict 在 `agent_end` 时持久化到 `thread_extra`。+- `AgentContext` 的 `extra` dict 会在产生工具结果的轮次结束之后、HITL 暂停(`agent_suspended`)时,以及 `agent_end` 时写入 `thread_extra`。Middleware 需要持久化线程级状态时,往 `context.extra` 写。这个 schema 是追加式的。CubeLoop 从不 update 或 delete 行。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/compaction.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/compaction.mdindex 2f1a410..ebf6919 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/compaction.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/compaction.md@@ -44,7 +44,7 @@ middleware 会向 `AgentContext.extra` 写入两个键:- `compaction` —— 摘要状态,以及它覆盖的消息引用。- `compaction_until_msg_index` —— 已总结到的历史边界。-绑定 checkpointer 时,CubeLoop 会在 `agent_end` 通过 `save_extra` 保存+绑定 checkpointer 时,CubeLoop 会在产生工具结果的轮次结束之后、HITL 暂停时,以及 `agent_end` 时通过 `save_extra` 保存`ctx.extra`,所以下一个进程可以带着已有摘要继续。如果消息引用与当前历史不再匹配,middleware 会清除旧状态并重新开始,而不是发送无效摘要。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/examples.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/examples.mdindex 4dd0f95..a333ccb 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/examples.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/examples.md@@ -130,7 +130,7 @@ class ToolLoggingMiddleware(Middleware):`ctx.context.extra` 是存储每次运行状态的最佳位置,因为:- 其他中间件可通过同一个 `ctx.context` 看到。-- Checkpointer 在 `agent_end` 时通过 `save_extra` 持久化。+- Checkpointer 在产生工具结果的轮次结束之后、运行暂停时,以及 `agent_end` 时通过 `save_extra` 持久化。- 新对话开始时(新的 `thread_id`)会自动重置。## 滑动窗口截断 {#sliding-window-truncation}@@ -163,6 +163,23 @@ class SummaryInjector(Middleware):return f"{system_prompt}\n\nContext: {summary}".strip()```+## 内置工具结果长度限制++`ToolResultLimitMiddleware` 在 `after_tool_call` 里截断过长的工具结果文本,避免一次 `execute`、抓取或 MCP 调用的输出撑破下一次模型请求,或超出宿主的事件大小限制。++```python+from cubeloop.middleware import ToolResultLimitMiddleware++agent = Agent(+ model=…,+ middleware=[+ ToolResultLimitMiddleware(max_chars=20_000),+ ],+)+```++选项、排除名单和放置顺序见[工具结果长度限制](./tool-result-limit.md)。+## 最大轮次 / 预算上限在达到最大轮次数或成本上限时硬停止 agent:diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/todo.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/todo.mdindex 8e53b5c..e47f7d9 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/todo.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/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,50 @@ 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+的初始消息或 HITL 答复(包括人工批准、拒绝或编辑工具调用)都会使旧声明失效。+策略自动批准不属于新的人工输入;压缩上下文后无法确认原输入边界时也需重新声明。++用户后来取消已验证的工作时,宿主证明取消发生在原校验之后,可返回+`status="cancelled"` 和非空 `reason`,允许自然收尾并保留未完成列表和取消原因。+cancelled 不能用来建立新声明。无效 ID、查询失败、旧绑定仍走原有守卫;不能借等待+绕过 Todo 参数错误、显式停止、HITL 或其他 middleware 的控制。++可恢复声明需要 checkpointer 和实时 extra 引用。工具轮次结束后、下一次模型调用前,+以及发布 HITL 暂停和正常结束时都会保存 extra;保存失败不算成功持久化等待声明。+CubeLoop 不负责启动、轮询、取消或+投递后台任务,也不保持等待中的 Session;宿主负责任务生命周期及后续输入或新 run。+没有 Todo 的 agent 不需要为了结束 run 而额外调用该工具。+## 过期提醒如果模型连续多轮不调用 `write_todos`,middleware 会注入一条软性提醒,请模型同步列表。模型可以忽略该提醒,它不是硬性阻断。@@ -107,6 +144,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` 的一部分持久化,恢复的会话会从模型上次保留的待办列表继续。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/tool-result-limit.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/tool-result-limit.mdnew file mode 100644index 0000000..f2842cf--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/guides/middleware/tool-result-limit.md@@ -0,0 +1,52 @@+---+title: 工具结果长度限制+description: "用 ToolResultLimitMiddleware 在 ToolExecutionEndEvent 发出前截断过长的工具结果文本。"+---++# 工具结果长度限制++`ToolResultLimitMiddleware` 在 `after_tool_call` 里截断过长的工具结果文本,发生在 CubeLoop 发布 `ToolExecutionEndEvent` 之前。模型、checkpointer 和宿主的事件消费者看到的都是截断后的结果。++工具可能返回不受控的输出时使用它,比如 shell、网页抓取、MCP 工具。过大的结果会撑破上下文窗口,或者超出宿主的事件大小限制。++## 基本设置++```python+from cubeloop import Agent+from cubeloop.middleware import ToolResultLimitMiddleware++agent = Agent(+ model=provider.model("claude-sonnet-4-6"),+ middleware=[+ ToolResultLimitMiddleware(),+ ],+)+```++默认上限是 20,000 个字符的文本内容。不超过上限的结果原样通过(`after_tool_call` 返回 `None`)。超过上限时,文本保留前 `max_chars` 个字符,并附上提示:++```text+[truncated: tool result was 1082017 characters; showing first 20000. Narrow the tool call and retry.]+```++图片块会保留。只有 `TextContent` 计入上限。++## 选项++```python+ToolResultLimitMiddleware(+ max_chars=20_000,+ exclude_tool_names={"load_skill"},+)+```++- `max_chars`:从原始结果保留的最大文本字符数,必须 `>= 1`。+- `exclude_tool_names`:跳过截断的工具名。完整内容本身就是负载时使用,例如 `load_skill` 返回的 skill 正文。++## 放置顺序++把它放在其他 `after_tool_call` middleware **之后**,让它们先改写完整结果,再由截断后的文本进入 `ToolExecutionEndEvent`。++CubeLoop 默认的组合规则是最后一个非 `None` 返回值生效。排在后面的 middleware 如果返回了不含 `content` 的 `AfterToolCallResult`,这次改写会被丢掉。把 `ToolResultLimitMiddleware` 放在最后,或者换一个会合并 `content` 和 `details` 的 composer。++子 agent 不会继承父 agent 的 middleware。如果子工具的结果也要限制,通过 `SubagentMiddleware(inherited_middleware=...)` 传入同一个实例或再创建一个。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/intro.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/intro.mdxindex 29fd17d..5b2f6ea 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/intro.mdx+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/intro.mdx@@ -73,5 +73,7 @@ CubeLoop 0.15 增加 Execution Session,供宿主获取明确的执行结果、输入,并跟踪检查点提交后的事件交付。详见[核心概念](./getting-started/core-concepts.md)和 [API 参考](./api/index.mdx)。+0.15.1 增加工具结果文本上限,并允许 `TodoListMiddleware` 在宿主已校验的后台任务尚未完成时结束当前 run。见[工具结果长度限制](./guides/middleware/tool-result-limit.md)和[待办列表](./guides/middleware/todo.md)。+源代码、Issue 和讨论都在[GitHub](https://github.com/cubeplexai/cubeloop)。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/recipes/sandbox-confirm.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/recipes/sandbox-confirm.mdindex decaeb9..90e1051 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/recipes/sandbox-confirm.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.15/recipes/sandbox-confirm.md@@ -110,7 +110,7 @@ async def host_loop(channel: CheckpointedChannel):| 人类选择 | 工具结果 | `hitl_trace["decision"]` | 模型看到 ||---|---|---|---|-| 批准 | 使用原始参数执行 | 未设置(直通,无 HITL 细节) | 正常 `tool_result` |+| 批准 | 使用原始参数执行 | `"human_approve"` | 正常 `tool_result` || 拒绝 | 被阻止 | `"human_deny"` | `tool_result.is_error=True` 及用户的原因 || 编辑 | 使用编辑后的参数执行 | `"edit"` + `original_args` / `edited_args` | 正常 `tool_result`(来自编辑后的执行) |diff --git a/website/versioned_docs/version-0.15/api/cubeloop-middleware.mdx b/website/versioned_docs/version-0.15/api/cubeloop-middleware.mdxindex 9f9ff5a..f536489 100644--- a/website/versioned_docs/version-0.15/api/cubeloop-middleware.mdx+++ b/website/versioned_docs/version-0.15/api/cubeloop-middleware.mdx@@ -215,6 +215,52 @@ compose_middleware(middlewares: list[Middleware]) -> dict[str, Callable][source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/base.py#L145)+### TaskWaitBinding {#taskwaitbinding}++_class_++A successful host check bound to the checklist and committed input boundary.++[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L286)+++**Attributes**++- `task_ids`: `list[str]`+- `todos`: `list[Todo]`+- `run_id`: `str | None`+- `input_boundary`: `str`+- `validation`: `JsonObject`+++### TaskWaitValidation {#taskwaitvalidation}++_class_++Host evidence; cancelled is only meaningful for a prior successful binding.++[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L296)+++**Attributes**++- `status`: `Literal['valid', 'cancelled', 'invalid']`+- `reason`: `str`+- `validation`: `JsonObject`+++### TaskWaitValidator {#taskwaitvalidator}++_attribute_++```python+TaskWaitValidator: TypeAlias = Callable[[list[str], AgentContext, TaskWaitBinding | None], Awaitable[TaskWaitValidation]]+```+++[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L304)++### CompactionMiddleware {#compactionmiddleware}_class_@@ -347,6 +393,51 @@ on_run_end(+### ToolResultLimitMiddleware {#toolresultlimitmiddleware}++_class_++```python+ToolResultLimitMiddleware(+ *,+ max_chars: int = DEFAULT_MAX_TOOL_RESULT_CHARS,+ exclude_tool_names: Collection[str] = (),+)+```++Rewrite oversized tool results in `after_tool_call`.++Place this after other `after_tool_call` middleware so the truncated+content is what later composition and `ToolExecutionEndEvent` see.+Under the default last-non-None composer, a later middleware that+returns a result without `content` will drop this rewrite — put this+last, or use a merging composer.++[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/tool_result_limit.py#L67)+++**Attributes**++- `max_chars`+- `exclude_tool_names`+++**Methods**++#### `after_tool_call` {#toolresultlimitmiddleware-after-tool-call}++```python+after_tool_call(+ ctx: AfterToolCallContext,+ *,+ signal: asyncio.Event | None = None,+) -> AfterToolCallResult | None+```++[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/tool_result_limit.py#L88)+++### SubagentMiddleware {#subagentmiddleware}_class_@@ -454,7 +545,7 @@ _class_A single todo item with content and status.-[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L132)+[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L146)**Attributes**@@ -469,7 +560,7 @@ _class_A guard escalation payload carried across the forced end turn.-[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L149)+[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L163)**Attributes**@@ -521,6 +612,7 @@ TodoListMiddleware(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,)```@@ -544,7 +636,7 @@ Hooks:* finalization hard guard → loop_to_model with correction message* otherwise → return None (natural flow)-[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L466)+[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L557)**Attributes**@@ -554,6 +646,19 @@ Hooks:**Methods**+#### `before_tool_call` {#todolistmiddleware-before-tool-call}++```python+before_tool_call(+ ctx: BeforeToolCallContext,+ *,+ signal: asyncio.Event | None = None,+) -> BeforeToolCallResult | None+```++[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L602)++#### `transform_system_prompt` {#todolistmiddleware-transform-system-prompt}```python@@ -567,7 +672,7 @@ transform_system_prompt(Append the write_todos system instructions.-[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L508)+[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L701)#### `transform_context` {#todolistmiddleware-transform-context}@@ -589,7 +694,7 @@ context to ensure the model always sees the current todo list.When no todos are set, messages are returned unchanged (no injection).-[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L523)+[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L716)#### `after_tool_call` {#todolistmiddleware-after-tool-call}@@ -612,7 +717,7 @@ in extra["_todos_snapshot"]. Each duplicate write_todos call's result isreplaced with an error here, and extra["todos"] is restored to the snapshotso the turn leaves the checklist unchanged.-[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L557)+[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L750)#### `after_model_response` {#todolistmiddleware-after-model-response}@@ -632,7 +737,7 @@ Inspects the latest assistant message, transitions the blocked /stale-iteration state stored in `extra`, and returns a`TurnAction` when the loop needs an injected nudge or hard stop.-[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L653)+[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L850)@@ -642,12 +747,13 @@ _class_Input schema for the `write_todos` tool.-[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L262)+[source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/middleware/todo.py#L276)**Attributes**- `todos`: `list[Todo]`+- `wait_for_tasks`: `list[str]`diff --git a/website/versioned_docs/version-0.15/guides/agents/multi-turn.md b/website/versioned_docs/version-0.15/guides/agents/multi-turn.mdindex cdb01cb..aa2a6f1 100644--- a/website/versioned_docs/version-0.15/guides/agents/multi-turn.md+++ b/website/versioned_docs/version-0.15/guides/agents/multi-turn.md@@ -156,7 +156,8 @@ async with SQLiteCheckpointer("conv.db") as cp:The checkpoint `extra` mapping is also restored. Middleware that wants topersist per-thread state should write into `context.extra`; the checkpointer's-`save_extra` is called at `agent_end`. Hosts should use+`save_extra` is called after a turn that produced tool results, when the run+suspends, and at `agent_end`. Hosts should use`agent.session.state_context`, which is the stable live mapping, and`await agent.session.load_checkpoint()` when they need an explicit idle-timerestore. Messages and extra are installed together, including checkpointsdiff --git a/website/versioned_docs/version-0.15/guides/checkpointing/custom.md b/website/versioned_docs/version-0.15/guides/checkpointing/custom.mdindex 69a98c9..eaf5e11 100644--- a/website/versioned_docs/version-0.15/guides/checkpointing/custom.md+++ b/website/versioned_docs/version-0.15/guides/checkpointing/custom.md@@ -30,7 +30,7 @@ in-memory dict — anything that can append-and-list.|---|---|| `load(thread_id)` | Once, on the first `prompt()` after agent construction || `append(thread_id, messages)` | Inside `message_end`, every time a message is finalised |-| `save_extra(thread_id, extra)` | At `agent_end`, with the current `_extra` dict |+| `save_extra(thread_id, extra)` | After a turn that produced tool results, on `agent_suspended`, and at `agent_end`, with the current `_extra` dict |`load` returns `None` for unknown threads. `append` and `save_extra`do nothing useful if you don't already have a thread; create the rowdiff --git a/website/versioned_docs/version-0.15/guides/checkpointing/sqlite.md b/website/versioned_docs/version-0.15/guides/checkpointing/sqlite.mdindex 5d8b024..78873f8 100644--- a/website/versioned_docs/version-0.15/guides/checkpointing/sqlite.md+++ b/website/versioned_docs/version-0.15/guides/checkpointing/sqlite.md@@ -76,9 +76,10 @@ CREATE TABLE thread_extra (- Every `UserMessage`, `AssistantMessage`, and `ToolResultMessage`becomes one row in `messages`. Pydantic `model_dump()` is used forthe JSON payload.-- The `extra` dict on `AgentContext` is persisted on `agent_end` into- `thread_extra`. Middleware that wants thread-scoped state should- write into `context.extra`.+- The `extra` dict on `AgentContext` is persisted into `thread_extra`+ after a turn that produced tool results, on HITL suspension+ (`agent_suspended`), and at `agent_end`. Middleware that wants+ thread-scoped state should write into `context.extra`.This schema is append-only. CubeLoop never updates or deletes rows.diff --git a/website/versioned_docs/version-0.15/guides/middleware/compaction.md b/website/versioned_docs/version-0.15/guides/middleware/compaction.mdindex 8bcf146..06a47a6 100644--- a/website/versioned_docs/version-0.15/guides/middleware/compaction.md+++ b/website/versioned_docs/version-0.15/guides/middleware/compaction.md@@ -48,7 +48,7 @@ The middleware writes two keys into `AgentContext.extra`:- `compaction` — the summary state and the message refs it covers.- `compaction_until_msg_index` — the history boundary summarized so far.-When a checkpointer is attached, CubeLoop saves `ctx.extra` at `agent_end`, so the+When a checkpointer is attached, CubeLoop saves `ctx.extra` after a turn that produced tool results, on HITL suspension, and at `agent_end`, so thenext process can resume with the existing summary. If the message refs no longermatch the current history, the middleware clears the stale state and starts overrather than sending an invalid summary.diff --git a/website/versioned_docs/version-0.15/guides/middleware/examples.md b/website/versioned_docs/version-0.15/guides/middleware/examples.mdindex 0b0b674..9a76835 100644--- a/website/versioned_docs/version-0.15/guides/middleware/examples.md+++ b/website/versioned_docs/version-0.15/guides/middleware/examples.md@@ -136,7 +136,7 @@ class ToolLoggingMiddleware(Middleware):it's:- Visible to other middleware via the same `ctx.context`.-- Persisted by checkpointers via `save_extra` at `agent_end`.+- Persisted by checkpointers via `save_extra` after tool-result turns, on suspension, and at `agent_end`.- Reset when a new conversation starts (a new `thread_id`).## Sliding-window truncation@@ -171,6 +171,26 @@ class SummaryInjector(Middleware):return f"{system_prompt}\n\nContext: {summary}".strip()```+## Built-in tool-result cap++`ToolResultLimitMiddleware` truncates oversized tool-result text in+`after_tool_call` so a runaway `execute` / fetch / MCP payload cannot+blow the next model call (or a host event-size budget).++```python+from cubeloop.middleware import ToolResultLimitMiddleware++agent = Agent(+ model=…,+ middleware=[+ ToolResultLimitMiddleware(max_chars=20_000),+ ],+)+```++See [Tool Result Limit](./tool-result-limit.md) for options, exclusions,+and placement.+## Built-in compaction`CompactionMiddleware` summarizes older turns into `ctx.extra` anddiff --git a/website/versioned_docs/version-0.15/guides/middleware/todo.md b/website/versioned_docs/version-0.15/guides/middleware/todo.mdindex 213b2aa..c4cb31b 100644--- a/website/versioned_docs/version-0.15/guides/middleware/todo.md+++ b/website/versioned_docs/version-0.15/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,62 @@ 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 or a HITL answer (including approval, denial, or editing of a tool call),+invalidates it. Automatic policy approval is not new human input. 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 +174,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/versioned_docs/version-0.15/guides/middleware/tool-result-limit.md b/website/versioned_docs/version-0.15/guides/middleware/tool-result-limit.mdnew file mode 100644index 0000000..41095f7--- /dev/null+++ b/website/versioned_docs/version-0.15/guides/middleware/tool-result-limit.md@@ -0,0 +1,70 @@+---+title: Tool Result Limit+description: "Use ToolResultLimitMiddleware to cap tool-result text before it is emitted to the model and host event consumers."+---++# Tool Result Limit++`ToolResultLimitMiddleware` truncates oversized tool-result text in+`after_tool_call`, before CubeLoop publishes `ToolExecutionEndEvent`.+The model, the checkpointer, and any host event consumer all see the+truncated result.++Use it when a tool can return unbounded output — shell commands,+web fetches, MCP tools — and a huge result would blow the context+window or a host event-size budget.++## Basic setup++```python+from cubeloop import Agent+from cubeloop.middleware import ToolResultLimitMiddleware++agent = Agent(+ model=provider.model("claude-sonnet-4-6"),+ middleware=[+ ToolResultLimitMiddleware(),+ ],+)+```++The default cap is 20,000 characters of text content. Results at or+under the cap pass through unchanged (`after_tool_call` returns+`None`). Over the cap, text is cut to the first `max_chars` characters+and a notice is appended:++```text+[truncated: tool result was 1082017 characters; showing first 20000. Narrow the tool call and retry.]+```++Image blocks are kept. Only `TextContent` counts toward the cap.++## Options++```python+ToolResultLimitMiddleware(+ max_chars=20_000,+ exclude_tool_names={"load_skill"},+)+```++- `max_chars` — maximum characters of text kept from the original+ result. Must be `>= 1`.+- `exclude_tool_names` — tool names that skip truncation. Use this for+ tools whose full payload is load-bearing (for example a skill body+ returned by `load_skill`).++## Placement++Put this **after** other `after_tool_call` middleware so they rewrite+the full result first, and the truncated text is what+`ToolExecutionEndEvent` carries.++CubeLoop's default composer is last-non-`None` wins. A later+middleware that returns an `AfterToolCallResult` without `content`+would drop this rewrite. Keep `ToolResultLimitMiddleware` last, or+use a composer that merges `content` and `details`.++Subagent child agents do not inherit parent middleware. Pass the same+instance (or a second one) via `SubagentMiddleware(inherited_middleware=...)`+if child tool results should be capped too.diff --git a/website/versioned_docs/version-0.15/intro.mdx b/website/versioned_docs/version-0.15/intro.mdxindex 5ff52cb..db94a20 100644--- a/website/versioned_docs/version-0.15/intro.mdx+++ b/website/versioned_docs/version-0.15/intro.mdx@@ -80,5 +80,10 @@ outcomes, identified input, and checkpoint-aware event delivery. See[Core Concepts](./getting-started/core-concepts.md) and the[API Reference](./api/index.mdx).+0.15.1 adds a tool-result text cap and lets `TodoListMiddleware` finish a+run while host-validated background tasks are still open. See+[Tool Result Limit](./guides/middleware/tool-result-limit.md) and+[Todo List](./guides/middleware/todo.md).+Source, issues, and discussion live on[GitHub](https://github.com/cubeplexai/cubeloop).diff --git a/website/versioned_docs/version-0.15/recipes/sandbox-confirm.md b/website/versioned_docs/version-0.15/recipes/sandbox-confirm.mdindex 3736dce..310d03e 100644--- a/website/versioned_docs/version-0.15/recipes/sandbox-confirm.md+++ b/website/versioned_docs/version-0.15/recipes/sandbox-confirm.md@@ -111,7 +111,7 @@ async def host_loop(channel: CheckpointedChannel):| Human chose | Tool outcome | `hitl_trace["decision"]` | Model sees ||---|---|---|---|-| Approve | Runs with original args | unset (passthrough, no HITL details) | Normal `tool_result` |+| Approve | Runs with original args | `"human_approve"` | Normal `tool_result` || Deny | Blocked | `"human_deny"` | `tool_result.is_error=True` with user's reason || Edit | Runs with edited args | `"edit"` + `original_args` / `edited_args` | Normal `tool_result` (from the edited execution) |diff --git a/website/versioned_sidebars/version-0.15-sidebars.json b/website/versioned_sidebars/version-0.15-sidebars.jsonindex 41ac270..10ec845 100644--- a/website/versioned_sidebars/version-0.15-sidebars.json+++ b/website/versioned_sidebars/version-0.15-sidebars.json@@ -58,6 +58,7 @@"guides/middleware/compaction","guides/middleware/subagents","guides/middleware/todo",+ "guides/middleware/tool-result-limit","guides/middleware/deferred-tools","guides/middleware/goal","guides/middleware/examples"