CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
docs: add on_run_end hook to all middleware docs (7→8 hooks); fix stale SKILL.md
xf gong3371e40c2b7e
diff --git a/skills/cubepi/SKILL.md b/skills/cubepi/SKILL.mdindex 3b0351a..0de6d25 100644--- a/skills/cubepi/SKILL.md+++ b/skills/cubepi/SKILL.md@@ -78,21 +78,48 @@ https://cubepi.ai/docs/guides/streaming### Middleware-Seven typed hooks (`before_model_request`, `after_model_response`,-`before_tool_call`, `after_tool_call`, `on_turn_start`, `on_turn_end`,-`on_agent_end`). Declare with `@middleware` and compose with `compose_middleware`:+Eight typed hooks. Subclass `Middleware`, override the hooks you need, pass instances+to `Agent(middleware=[...])`:```python-from cubepi.middleware import middleware, compose_middleware+from cubepi import Middleware-@middleware-async def log_calls(ctx, next):- print(f"tool: {ctx.tool_name}")- return await next(ctx)+class MyMiddleware(Middleware):+ async def transform_context(self, messages, *, signal=None):+ return messages # filter / inject messages before each LLM call-agent = Agent(..., middleware=compose_middleware(log_calls, other_middleware))+ async def transform_system_prompt(self, sp, *, signal=None):+ return sp + "\nExtra." # append to system prompt++ async def before_tool_call(self, ctx, *, signal=None):+ return None # BeforeToolCallResult(block=True) to deny++ async def after_tool_call(self, ctx, *, signal=None):+ return None # AfterToolCallResult(...) to override result++ async def after_model_response(self, response, ctx, *, signal=None):+ return None # TurnAction(decision="stop"|"loop_to_model")++ async def should_stop_after_turn(self, ctx) -> bool:+ return False # True to end run after this turn++ async def on_run_end(self, ctx, *, signal=None):+ return None # list[Message] to inject + run one extra turn++agent = Agent(..., middleware=[MyMiddleware()])```+| Hook | Fires | Composition |+|---|---|---|+| `transform_context` | Before each model call | Chained |+| `convert_to_llm` | Right before serialisation | Last wins |+| `transform_system_prompt` | Before each model call | Chained |+| `before_tool_call` | Per tool call | First block stops |+| `after_tool_call` | Per tool call | Later overrides earlier |+| `after_model_response` | After assistant message | Chain; last decision wins |+| `should_stop_after_turn` | Each turn boundary | Any True stops |+| `on_run_end` | Once after all turns, before agent_end | Messages concatenate |+Full docs: https://cubepi.ai/docs/guides/middleware### Checkpointingdiff --git a/website/docs/getting-started/core-concepts.md b/website/docs/getting-started/core-concepts.mdindex c6bac97..8d9df22 100644--- a/website/docs/getting-started/core-concepts.md+++ b/website/docs/getting-started/core-concepts.md@@ -112,7 +112,7 @@ Subscribe to agent events for UI; for low-level token routing dig into## Middleware-`Middleware` is a class with up to seven typed hooks:+`Middleware` is a class with up to eight typed hooks:| Hook | When it runs | Composition rule ||---|---|---|@@ -123,6 +123,7 @@ Subscribe to agent events for UI; for low-level token routing dig into| `after_tool_call` | Per tool call, after `execute` | Later override earlier || `after_model_response` | After the assistant message lands | Returns a `TurnAction` controlling flow || `should_stop_after_turn` | At each turn boundary | Any `True` stops |+| `on_run_end` | Once after all turns complete, before `agent_end` | Messages concatenate; non-empty triggers one extra turn |Pass middleware as a list to `Agent(middleware=[...])`. See[Middleware → Composition](../guides/middleware/composition).diff --git a/website/docs/guides/middleware/composition.md b/website/docs/guides/middleware/composition.mdindex b5315be..0264e96 100644--- a/website/docs/guides/middleware/composition.md+++ b/website/docs/guides/middleware/composition.md@@ -22,6 +22,7 @@ to remember "before" or "after" precedence guesses.| `after_tool_call` | **Later overrides earlier** | Last write wins || `should_stop_after_turn` | **Any `True` stops** (OR) | No || `after_model_response` | **Chain with merge semantics** | See below |+| `on_run_end` | **Messages concatenate** — non-empty triggers one extra turn | No |## `transform_context` and `transform_system_prompt`@@ -170,7 +171,15 @@ class JustTransform(Middleware):# No other hooks. CubePi won't call them.```+## `on_run_end`++All middleware returning non-empty lists contribute; their messages are+concatenated into a single list and injected before the extra model+turn. Middleware returning `None` or `[]` are skipped. Because all+contribute, order doesn't affect whether messages are injected — only+their relative order within the injected list.+## See also-- [The 7 Hooks](./hooks) — what each hook does and when it fires.+- [The 8 Hooks](./hooks) — what each hook does and when it fires.- [Examples](./examples) — composition in practice.diff --git a/website/docs/guides/middleware/hooks.md b/website/docs/guides/middleware/hooks.mdindex a2ed5c4..81a8d90 100644--- a/website/docs/guides/middleware/hooks.md+++ b/website/docs/guides/middleware/hooks.md@@ -1,11 +1,11 @@----title: The 7 Hooks-description: "Reference for the 7 middleware hooks in CubePi — transform_context, convert_to_llm, before_tool_call, after_tool_call, and more."+title: The 8 Hooks+description: "Reference for the 8 middleware hooks in CubePi — transform_context, convert_to_llm, before_tool_call, after_tool_call, on_run_end, and more."----# The 7 Hooks+# The 8 Hooks-`Middleware` is a class with up to seven optional async methods. Each+`Middleware` is a class with up to eight optional async methods. Eachhook fires at a precise point in the agent loop. Implement only theones you need — CubePi only wires in the ones you override.@@ -176,6 +176,43 @@ Composition: chain — each middleware sees the previousmiddleware's `response`; `inject_messages` concatenate across thechain; the last middleware's `decision` wins.+## `on_run_end`++```python+async def on_run_end(+ self,+ ctx: AgentContext,+ *,+ signal=None,+) -> list[Message] | None:+ ...+```++Fires **once per `prompt()` call**, after all turns and tool calls+complete, before `AgentEndEvent` is emitted. Return a non-empty+`list[Message]` to inject those messages into context and run **one+extra model turn** (the run-end pass). Return `None` or `[]` to do+nothing.++The extra turn fires exactly once — a `_reflection_fired` guard in the+loop prevents the injected turn from triggering another `on_run_end`.++**When it fires:**+- Normal completion (loop breaks naturally after all turns).+- `should_stop_after_turn` returns `True`.+- `after_model_response` returns `decision="stop"`.++**When it does NOT fire:**+- The run ends with `stop_reason` `"error"` or `"aborted"`.+- HITL interruption (`HitlDetached` / `HitlAborted`) — the run is+ paused, not finished.++Use for: post-run memory consolidation, conversation summarisation,+audit logging that needs the full turn context.++Composition: messages from all middleware **concatenate** into a single+list; all are injected together before the extra model turn.+## Anatomy of a middlewareA middleware doesn't have to implement every hook. Only override the@@ -204,4 +241,4 @@ agent = Agent(provider=…, model=…, middleware=[MaxTurnsMiddleware(5)])- [Composition Rules](./composition) — exact semantics when multiplemiddlewares define the same hook.- [Examples](./examples) — working middleware for rate limiting,- logging, retries, sliding-window context.+ logging, retries, sliding-window context, post-run memory.diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.mdindex 01d0ebf..d86c151 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md@@ -104,7 +104,7 @@ class Provider(Protocol):## Middleware-`Middleware` 是有最多七个类型化 hook 的类:+`Middleware` 是有最多八个类型化 hook 的类:| Hook | 何时触发 | 组合规则 ||---|---|---|@@ -115,6 +115,7 @@ class Provider(Protocol):| `after_tool_call` | 每个工具调用之后(在 `execute` 之后) | 后写覆盖先写 || `after_model_response` | assistant 消息落定之后 | 返回 `TurnAction` 控制流向 || `should_stop_after_turn` | 每个轮次结束时 | 任一返回 `True` 即停 |+| `on_run_end` | 所有轮次完成后一次,`agent_end` 之前 | 消息拼接;非空触发一轮额外调用 |通过 `Agent(middleware=[...])` 传入。见[Middleware → 组合规则](../guides/middleware/composition)。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/composition.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/composition.mdindex 3a2df01..353b343 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/composition.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/composition.md@@ -20,6 +20,7 @@ description: "了解 CubePi 如何通过 per-hook 规则组合多个中间件。| `after_tool_call` | **后面覆盖前面** | 最后写入胜出 || `should_stop_after_turn` | **任一 True 即停止**(OR) | 否 || `after_model_response` | **带合并语义的链式** | 见下文 |+| `on_run_end` | **消息拼接**——非空触发一轮额外调用 | 否 |## `transform_context` 和 `transform_system_prompt`@@ -151,7 +152,13 @@ class JustTransform(Middleware):# 没有其他 hook。CubePi 不会调用它们。```+## `on_run_end`++所有返回非空列表的中间件都会贡献消息;消息拼接为单一列表,在额外模型轮次+之前注入。返回 `None` 或 `[]` 的中间件被跳过。由于所有中间件都贡献,顺序+不影响消息是否被注入——只影响注入列表内的相对顺序。+## 另请参阅-- [7 个 Hook](./hooks) —— 每个 hook 的作用及触发时机。+- [8 个 Hook](./hooks) —— 每个 hook 的作用及触发时机。- [示例](./examples) —— 组合在实践中的应用。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/hooks.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/hooks.mdindex 764dbfd..2adf752 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/hooks.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/hooks.md@@ -1,11 +1,11 @@----title: 7 个 Hook-description: "CubePi 的 7 个中间件 hook 参考——transform_context、before_tool_call、after_tool_call 等。"+title: 8 个 Hook+description: "CubePi 的 8 个中间件 hook 参考——transform_context、before_tool_call、after_tool_call、on_run_end 等。"----# 7 个 Hook+# 8 个 Hook-`Middleware` 是一个最多包含七个可选异步方法的类。每个 hook 在 agent+`Middleware` 是一个最多包含八个可选异步方法的类。每个 hook 在 agent循环中的精确位置触发。只实现你需要的——CubePi 只会连接你重写了的方法。```python@@ -163,6 +163,38 @@ TurnAction(组合方式:链式——每个中间件看到前一个中间件的 `response`;`inject_messages` 跨链拼接;最后一个中间件的 `decision` 胜出。+## `on_run_end`++```python+async def on_run_end(+ self,+ ctx: AgentContext,+ *,+ signal=None,+) -> list[Message] | None:+ ...+```++**每次 `prompt()` 调用结束时触发一次**——所有轮次和工具调用完成后、+`AgentEndEvent` 发出前。返回非空 `list[Message]` 会将这些消息注入上下文+并运行**一轮额外的模型调用**(run-end pass)。返回 `None` 或 `[]` 不做任何操作。++额外轮次只触发一次——循环内的 `_reflection_fired` 标志阻止注入轮次再次触发+`on_run_end`。++**何时触发:**+- 正常完成(所有轮次结束后循环自然 break)。+- `should_stop_after_turn` 返回 `True`。+- `after_model_response` 返回 `decision="stop"`。++**何时不触发:**+- run 以 `stop_reason` 为 `"error"` 或 `"aborted"` 结束。+- HITL 中断(`HitlDetached` / `HitlAborted`)——run 是暂停而非结束。++用于:run 结束后的记忆提炼、对话摘要、需要完整轮次上下文的审计日志。++组合方式:所有中间件返回的消息**拼接**为单一列表,一起注入额外模型轮次。+## 中间件的构成一个中间件不需要实现每一个 hook。只覆盖你需要的即可;基类中未实现@@ -187,4 +219,4 @@ agent = Agent(provider=…, model=…, middleware=[MaxTurnsMiddleware(5)])## 另请参阅- [组合规则](./composition) —— 多个中间件定义同一 hook 时的精确语义。-- [示例](./examples) —— 速率限制、日志、重试、滑动窗口上下文的实用中间件。+- [示例](./examples) —— 速率限制、日志、重试、滑动窗口上下文、run 结束后记忆的实用中间件。