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(seo): add SEO meta + zh-Hans doc translations
xf gongf149b56012a6
diff --git a/website/docs/api/index.mdx b/website/docs/api/index.mdxindex 3da8881..0765f52 100644--- a/website/docs/api/index.mdx+++ b/website/docs/api/index.mdx@@ -1,5 +1,6 @@---title: API Reference+description: "Reference documentation for the CubePi Python API."---# API Referencediff --git a/website/docs/getting-started/core-concepts.md b/website/docs/getting-started/core-concepts.mdindex e9bd4e5..be85302 100644--- a/website/docs/getting-started/core-concepts.md+++ b/website/docs/getting-started/core-concepts.md@@ -1,5 +1,6 @@---title: Core Concepts+description: "Learn the six core concepts of CubePi: Agent, Tool, Provider, Stream & Events, Middleware, and Checkpointer."---# Core Conceptsdiff --git a/website/docs/getting-started/installation.md b/website/docs/getting-started/installation.mdindex 72c8939..7e2c560 100644--- a/website/docs/getting-started/installation.md+++ b/website/docs/getting-started/installation.md@@ -1,5 +1,6 @@---title: Installation+description: "Install CubePi via pip. Python 3.11+ required. Supports Linux, macOS, and Windows."---# Installationdiff --git a/website/docs/getting-started/quick-start.md b/website/docs/getting-started/quick-start.mdindex a0ff7de..aa98eb9 100644--- a/website/docs/getting-started/quick-start.md+++ b/website/docs/getting-started/quick-start.md@@ -1,5 +1,6 @@---title: Quick Start+description: "Build your first CubePi agent in minutes with this step-by-step quick-start guide."---# Quick Startdiff --git a/website/docs/guides/agents/first-agent.md b/website/docs/guides/agents/first-agent.mdindex 0783d05..4bf1df0 100644--- a/website/docs/guides/agents/first-agent.md+++ b/website/docs/guides/agents/first-agent.md@@ -1,5 +1,6 @@---title: Building Your First Agent+description: "Create and run your first CubePi agent — choose a provider, define a system prompt, and send a message."---# Building Your First Agentdiff --git a/website/docs/guides/agents/multi-turn.md b/website/docs/guides/agents/multi-turn.mdindex d238bfc..4a525f0 100644--- a/website/docs/guides/agents/multi-turn.md+++ b/website/docs/guides/agents/multi-turn.md@@ -1,5 +1,6 @@---title: Multi-turn Conversations+description: "Build multi-turn conversational agents with CubePi's stateful agent loop and message history."---# Multi-turn Conversationsdiff --git a/website/docs/guides/agents/streaming.md b/website/docs/guides/agents/streaming.mdindex c55baf0..288931d 100644--- a/website/docs/guides/agents/streaming.md+++ b/website/docs/guides/agents/streaming.md@@ -1,5 +1,6 @@---title: Streaming Events+description: "Stream events and tokens from CubePi agents in real time using subscribers and MessageStream."---# Streaming Eventsdiff --git a/website/docs/guides/agents/tool-use.md b/website/docs/guides/agents/tool-use.mdindex 7efa9e7..300db1f 100644--- a/website/docs/guides/agents/tool-use.md+++ b/website/docs/guides/agents/tool-use.md@@ -1,5 +1,6 @@---title: Tool Use & Parallel Execution+description: "Register tools, execute them in parallel or sequentially, and handle results with Pydantic validation in CubePi."---# Tool Use & Parallel Executiondiff --git a/website/docs/guides/checkpointing/custom.md b/website/docs/guides/checkpointing/custom.mdindex 1d7bd49..e36e0b5 100644--- a/website/docs/guides/checkpointing/custom.md+++ b/website/docs/guides/checkpointing/custom.md@@ -1,5 +1,6 @@---title: Custom Backends+description: "Implement a custom checkpointer backend for CubePi using the Checkpointer protocol."---# Custom Checkpointing Backendsdiff --git a/website/docs/guides/checkpointing/mysql.md b/website/docs/guides/checkpointing/mysql.mdindex 42fbce4..e9a6e63 100644--- a/website/docs/guides/checkpointing/mysql.md+++ b/website/docs/guides/checkpointing/mysql.md@@ -1,5 +1,6 @@---title: MySQL Checkpointing+description: "Use MySQLCheckpointer for persistent agent state in CubePi with the MySQL backend."---# MySQL Checkpointingdiff --git a/website/docs/guides/checkpointing/postgres.md b/website/docs/guides/checkpointing/postgres.mdindex 058ff71..851aa02 100644--- a/website/docs/guides/checkpointing/postgres.md+++ b/website/docs/guides/checkpointing/postgres.md@@ -1,5 +1,6 @@---title: Postgres Checkpointing+description: "Use PostgresCheckpointer for production-grade agent state persistence with asyncpg and advisory locks."---# Postgres Checkpointingdiff --git a/website/docs/guides/checkpointing/sqlite.md b/website/docs/guides/checkpointing/sqlite.mdindex f872f09..f5a3917 100644--- a/website/docs/guides/checkpointing/sqlite.md+++ b/website/docs/guides/checkpointing/sqlite.md@@ -1,5 +1,6 @@---title: SQLite Checkpointing+description: "Use SQLiteCheckpointer for lightweight single-process agent state persistence in CubePi."---# SQLite Checkpointingdiff --git a/website/docs/guides/hitl.md b/website/docs/guides/hitl.mdindex a9338ae..b392ca9 100644--- a/website/docs/guides/hitl.md+++ b/website/docs/guides/hitl.md@@ -1,5 +1,6 @@---title: Human-in-the-Loop (HITL)+description: "Add human-in-the-loop pauses to your CubePi agent with confirm, approve, and structured ask verbs."sidebar_position: 10---diff --git a/website/docs/guides/mcp/auth.md b/website/docs/guides/mcp/auth.mdindex 0dc729c..d40ecd5 100644--- a/website/docs/guides/mcp/auth.md+++ b/website/docs/guides/mcp/auth.md@@ -1,5 +1,6 @@---title: MCP Server Authentication+description: "Configure authentication — API keys, OAuth, and custom headers — for MCP servers in CubePi."---# MCP Server Authenticationdiff --git a/website/docs/guides/mcp/loading.md b/website/docs/guides/mcp/loading.mdindex 2cf6f27..93e1646 100644--- a/website/docs/guides/mcp/loading.md+++ b/website/docs/guides/mcp/loading.md@@ -1,5 +1,6 @@---title: Loading MCP Tools+description: "Load tools from MCP servers into your CubePi agent, including SSE-based remote servers."---# Loading MCP Toolsdiff --git a/website/docs/guides/middleware/composition.md b/website/docs/guides/middleware/composition.mdindex d0a4c02..b5315be 100644--- a/website/docs/guides/middleware/composition.md+++ b/website/docs/guides/middleware/composition.md@@ -1,5 +1,6 @@---title: Composition Rules+description: "Learn how CubePi composes multiple middlewares with per-hook rules: chain, last-wins, first-block-stops, and more."---# Composition Rulesdiff --git a/website/docs/guides/middleware/examples.md b/website/docs/guides/middleware/examples.mdindex cbf5184..ec52a80 100644--- a/website/docs/guides/middleware/examples.md+++ b/website/docs/guides/middleware/examples.md@@ -1,5 +1,6 @@---title: Examples+description: "Working middleware examples for CubePi: rate limiting, retries with backoff, structured logging, context truncation, and HITL."---# Middleware Examplesdiff --git a/website/docs/guides/middleware/hooks.md b/website/docs/guides/middleware/hooks.mdindex 09647ba..467a82d 100644--- a/website/docs/guides/middleware/hooks.md+++ b/website/docs/guides/middleware/hooks.md@@ -1,5 +1,6 @@---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."---# The 7 Hooksdiff --git a/website/docs/guides/providers/anthropic.md b/website/docs/guides/providers/anthropic.mdindex be42c2a..0da6971 100644--- a/website/docs/guides/providers/anthropic.md+++ b/website/docs/guides/providers/anthropic.md@@ -1,5 +1,6 @@---title: Anthropic+description: "Use Anthropic Claude models with CubePi's AnthropicProvider — supports thinking, caching, and tool use."---# Anthropic Providerdiff --git a/website/docs/guides/providers/capability-and-presets.md b/website/docs/guides/providers/capability-and-presets.mdindex 3c1085c..0727f6d 100644--- a/website/docs/guides/providers/capability-and-presets.md+++ b/website/docs/guides/providers/capability-and-presets.md@@ -1,5 +1,6 @@---title: Capability Descriptors+description: "Provider capabilities and model presets in CubePi — compare features across providers."---# Capability Descriptorsdiff --git a/website/docs/guides/providers/custom.md b/website/docs/guides/providers/custom.mdindex 3bfd97d..d6b91b1 100644--- a/website/docs/guides/providers/custom.md+++ b/website/docs/guides/providers/custom.md@@ -1,5 +1,6 @@---title: Writing a Custom Provider+description: "Write a custom provider for CubePi by implementing the Provider protocol."---# Writing a Custom Providerdiff --git a/website/docs/guides/providers/openai.md b/website/docs/guides/providers/openai.mdindex 06bb3bd..d27988c 100644--- a/website/docs/guides/providers/openai.md+++ b/website/docs/guides/providers/openai.md@@ -1,5 +1,6 @@---title: OpenAI+description: "Use OpenAI GPT models with CubePi's OpenAIProvider — Chat Completions API integration."---# OpenAI Providerdiff --git a/website/docs/guides/tracing/cli.md b/website/docs/guides/tracing/cli.mdindex 084266e..a6dcb8b 100644--- a/website/docs/guides/tracing/cli.md+++ b/website/docs/guides/tracing/cli.md@@ -1,5 +1,6 @@---title: The trace CLI+description: "Use the CubePi trace CLI to inspect, filter, and display OpenTelemetry trace spans."---# Inspecting traces with `cubepi trace`diff --git a/website/docs/guides/tracing/content-recording.md b/website/docs/guides/tracing/content-recording.mdindex 220102d..7063253 100644--- a/website/docs/guides/tracing/content-recording.md+++ b/website/docs/guides/tracing/content-recording.md@@ -1,5 +1,6 @@---title: Content & Redaction+description: "Configure prompt content recording and redaction in CubePi's OpenTelemetry tracing."sidebar_position: 4---diff --git a/website/docs/guides/tracing/getting-started.md b/website/docs/guides/tracing/getting-started.mdindex 0634a04..31445e8 100644--- a/website/docs/guides/tracing/getting-started.md+++ b/website/docs/guides/tracing/getting-started.md@@ -1,5 +1,6 @@---title: Getting Started+description: "Get started with OpenTelemetry tracing in CubePi — install, configure, and export spans."sidebar_position: 2---diff --git a/website/docs/guides/tracing/metrics.md b/website/docs/guides/tracing/metrics.mdindex 948e811..fc5d315 100644--- a/website/docs/guides/tracing/metrics.md+++ b/website/docs/guides/tracing/metrics.md@@ -1,5 +1,6 @@---title: Metrics+description: "Collect token usage, latency, and time-to-first-content metrics in CubePi tracing."sidebar_position: 5---diff --git a/website/docs/guides/tracing/otlp.md b/website/docs/guides/tracing/otlp.mdindex c93dd75..aaf5670 100644--- a/website/docs/guides/tracing/otlp.md+++ b/website/docs/guides/tracing/otlp.md@@ -1,5 +1,6 @@---title: OTLP & Backends+description: "Export CubePi OpenTelemetry traces to OTLP-compatible backends like Jaeger, Tempo, or Honeycomb."sidebar_position: 3---diff --git a/website/docs/guides/tracing/overview.md b/website/docs/guides/tracing/overview.mdindex ad0ba3b..83d211c 100644--- a/website/docs/guides/tracing/overview.md+++ b/website/docs/guides/tracing/overview.md@@ -1,5 +1,6 @@---title: Tracing Overview+description: "Overview of CubePi's OpenTelemetry-native tracing system — spans, attributes, exporters, and semantic conventions."sidebar_position: 1---diff --git a/website/docs/intro.mdx b/website/docs/intro.mdxindex e7317ab..128bd9f 100644--- a/website/docs/intro.mdx+++ b/website/docs/intro.mdx@@ -1,6 +1,7 @@---id: introtitle: CubePi+description: "A Pythonic, async-native alternative to langgraph and pi-agent-core.slug: /sidebar_position: 0---@@ -9,11 +10,11 @@ import PackageVersion from '@site/src/components/PackageVersion';# CubePi-**CubePi** is a Pythonic, async-native agent framework — a leaner, more-readable take on agent runtimes like-[langgraph](https://github.com/langchain-ai/langgraph). It models an-agent as a plain `async` function instead of a state graph; you can read-the entire core loop in five minutes.+**CubePi** is a Pythonic, async-native alternative to agent runtimes like+[langgraph](https://github.com/langchain-ai/langgraph) and+[pi-agent-core](https://github.com/anthropics/pi-agent-core). It models an+agent as a plain `async` function instead of a state graph; you can read the+entire core loop in five minutes.```bashpip install cubepidiff --git a/website/docs/migration/from-langgraph.md b/website/docs/migration/from-langgraph.mdindex e4e6c21..2214b18 100644--- a/website/docs/migration/from-langgraph.md+++ b/website/docs/migration/from-langgraph.md@@ -1,5 +1,6 @@---title: From langgraph+description: "Migrate your agents from LangGraph to CubePi."---# Migrating from langgraphdiff --git a/website/docs/recipes/ask-user-form.md b/website/docs/recipes/ask-user-form.mdindex 0bc3374..e0f1eee 100644--- a/website/docs/recipes/ask-user-form.md+++ b/website/docs/recipes/ask-user-form.md@@ -1,5 +1,6 @@---title: Multi-question Form via ask_user+description: "Build a multi-question form with CubePi's ask_user HITL tool for structured user input."---# Recipe: Multi-question Form via `ask_user`diff --git a/website/docs/recipes/multi-provider-failover.md b/website/docs/recipes/multi-provider-failover.mdindex 58e7210..f914daa 100644--- a/website/docs/recipes/multi-provider-failover.md+++ b/website/docs/recipes/multi-provider-failover.md@@ -1,5 +1,6 @@---title: Multi-Provider Failover+description: "Configure multi-provider failover in CubePi for resilience — automatic fallback between providers."---# Recipe: Multi-Provider Failoverdiff --git a/website/docs/recipes/persistent-chat.md b/website/docs/recipes/persistent-chat.mdindex df822e0..4ff1f15 100644--- a/website/docs/recipes/persistent-chat.md+++ b/website/docs/recipes/persistent-chat.md@@ -1,5 +1,6 @@---title: Persistent Chat+description: "Build a persistent chat application with CubePi and SQLiteCheckpointer."---# Recipe: Persistent Chat (SQLite)diff --git a/website/docs/recipes/postgres-fastapi.md b/website/docs/recipes/postgres-fastapi.mdindex d6c0421..2668a28 100644--- a/website/docs/recipes/postgres-fastapi.md+++ b/website/docs/recipes/postgres-fastapi.md@@ -1,5 +1,6 @@---title: Postgres + FastAPI Service+description: "Deploy a FastAPI-backed CubePi agent with PostgresCheckpointer for production."---# Recipe: Postgres + FastAPI Servicediff --git a/website/docs/recipes/resumable-tasks.md b/website/docs/recipes/resumable-tasks.mdindex 5a03f23..6b52af2 100644--- a/website/docs/recipes/resumable-tasks.md+++ b/website/docs/recipes/resumable-tasks.md@@ -1,5 +1,6 @@---title: Resumable Long Tasks+description: "Build crash-resilient long-running tasks with CubePi checkpointing and recovery."---# Recipe: Resumable Long Tasksdiff --git a/website/docs/recipes/sandbox-confirm.md b/website/docs/recipes/sandbox-confirm.mdindex e0eb804..3bd336a 100644--- a/website/docs/recipes/sandbox-confirm.md+++ b/website/docs/recipes/sandbox-confirm.md@@ -1,5 +1,6 @@---title: Sandbox Confirm with ApprovalPolicyMiddleware+description: "Implement sandbox tool confirmation with CubePi's ApprovalPolicyMiddleware — auto-allow, deny, or human-confirm."---# Recipe: Sandbox Confirm with `ApprovalPolicyMiddleware`diff --git a/website/docs/recipes/weather-agent.md b/website/docs/recipes/weather-agent.mdindex 96cc4d6..3253a23 100644--- a/website/docs/recipes/weather-agent.md+++ b/website/docs/recipes/weather-agent.md@@ -1,5 +1,6 @@---title: Weather Agent+description: "Build a weather agent that fetches live API data with CubePi tools."---# Recipe: Weather Agentdiff --git a/website/docusaurus.config.ts b/website/docusaurus.config.tsindex 922575d..ff41ad9 100644--- a/website/docusaurus.config.ts+++ b/website/docusaurus.config.ts@@ -40,11 +40,18 @@ const classicOptions: ClassicOptions = {theme: {customCss: './src/css/custom.css',},+ sitemap: {+ ignorePatterns: [+ '/docs/next/**',+ '/docs/0.3/**',+ '/docs/0.4/**',+ ],+ },};const config: Config = {title: 'CubePi',- tagline: 'A Pythonic, async-native agent framework',+ tagline: 'A Pythonic, async-native agent framework — an alternative to langgraph and pi-agent-core',favicon: 'img/brand/cubepi-logo.svg',url: 'https://cubepi.pages.dev',@@ -65,6 +72,23 @@ const config: Config = {},},+ headTags: [+ {+ tagName: 'script',+ attributes: { type: 'application/ld+json' },+ innerHTML: JSON.stringify({+ '@context': 'https://schema.org',+ '@type': 'SoftwareApplication',+ name: 'CubePi',+ description: 'A Pythonic, async-native alternative to langgraph and pi-agent-core. Plain async functions, append-only checkpointing, minimal dependencies.',+ url: 'https://cubepi.pages.dev',+ applicationCategory: 'DeveloperApplication',+ operatingSystem: 'Linux, macOS, Windows',+ programmingLanguage: 'Python',+ }),+ },+ ],+customFields: { POSTHOG_KEY, POSTHOG_HOST, GIT_SHA, PACKAGE_VERSION },clientModules: [require.resolve('./src/clientModules/posthog.ts')],@@ -76,12 +100,17 @@ const config: Config = {'@docusaurus/plugin-google-gtag',{trackingID: 'G-NE2PDN0M91',- anonymizeIP: false,+ anonymizeIP: true,},],],themeConfig: {+ metadata: [+ { name: 'keywords', content: 'CubePi, langgraph alternative, pi-agent-core alternative, Python agent framework, async agent, LLM agent, AI agent framework, tool-use agent' },+ { name: 'twitter:site', content: '@cubeplexai' },+ { name: 'twitter:creator', content: '@cubeplexai' },+ ],image: 'img/brand/cubepi-social-preview.png',navbar: {title: 'CubePi',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 978761a..2cb761e 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@@ -1,5 +1,6 @@---title: 核心概念+description: "了解 CubePi 的六个核心概念:Agent、Tool、Provider、Stream & Events、Middleware 和 Checkpointer。"---# 核心概念diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.mdindex d9c721e..e05b887 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.md@@ -1,5 +1,6 @@---title: 安装+description: "通过 pip 安装 CubePi。需要 Python 3.11+,支持 Linux、macOS 和 Windows。"---# 安装diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.mdindex 974721c..490deac 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md@@ -1,5 +1,6 @@---title: 快速开始+description: "在几分钟内构建你的第一个 CubePi agent。"---# 快速开始diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.mdindex f46e641..9166798 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md@@ -1,5 +1,6 @@---title: 第一个 Agent+description: "从零开始创建并运行你的第一个 CubePi agent。"---# 构建你的第一个 Agentdiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.mdindex bb7d7f1..d8451b6 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.md@@ -1,5 +1,6 @@---title: 流式输出+description: "通过 subscriber 和 MessageStream 实时流式接收 CubePi agent 的事件和 token。"---# 流式事件diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.mdindex 3f5e590..d01e361 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md@@ -1,5 +1,6 @@---title: 工具调用+description: "注册工具、并行或顺序执行、并通过 Pydantic 校验处理结果的完整指南。"---# 工具使用与并行执行diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.mdnew file mode 100644index 0000000..30e38fb--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.md@@ -0,0 +1,195 @@+---+title: Postgres 检查点+description: "使用 PostgresCheckpointer 实现生产级的 agent 状态持久化。"+---++# Postgres 检查点++`PostgresCheckpointer` 是生产级持久化后端。它使用 `asyncpg` 搭配连接池、+`msgpack` 编码 payload、以及每线程的 Postgres advisory lock,让多个进程+可以安全地写入同一个 `thread_id` 而不会互相干扰。++安装 extra:++```bash+pip install "cubepi[postgres]"+```++会拉入 `asyncpg`、`sqlalchemy` 和 `msgpack`。++## 基本用法++```python+import asyncio+from cubepi import Agent, Model+from cubepi.checkpointer import PostgresCheckpointer+from cubepi.providers.anthropic import AnthropicProvider+++async def main():+ provider = AnthropicProvider(api_key="…")+ async with PostgresCheckpointer("postgresql://user:pass@host/dbname") as cp:+ agent = Agent(+ provider=provider,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ checkpointer=cp,+ thread_id="user-42",+ )+ await agent.prompt("hello")+++asyncio.run(main())+```++DSN 接受 `asyncpg.create_pool(...)` 支持的任何格式。连接池大小:++```python+async with PostgresCheckpointer(+ "postgresql://…",+ min_pool_size=2,+ max_pool_size=20,+) as cp:+ …+```++## Schema++checkpointer 需要三张表:`cubepi_threads`、`cubepi_messages` 和+`cubepi_schema_version`。与 SQLite 不同,CubePi **不会自动创建这些表**——+它只在 `__aenter__` 时验证它们是否存在且 `schema_version` 是否匹配预期。++如果表不存在,你会收到 `CubepiSchemaUninitialized`。如果版本与本版+CubePi 不匹配,你会收到 `CubepiSchemaMismatch`。++原因:生产数据库属于宿主应用的迁移系统(Alembic、Atlas……),+不属于一个可能与你现有迁移冲突的第三方库。++### 通过 Alembic 引导++CubePi 暴露了 SQLAlchemy `MetaData`,让你的迁移可以采用其 schema:++```python+# alembic/env.py+from cubepi.checkpointer.postgres import cubepi_metadata, EXPECTED_SCHEMA_VERSION++target_metadata = [my_app_metadata, cubepi_metadata]+```++然后生成一个 revision 并执行。迁移还必须在 `cubepi_schema_version` 中+INSERT schema 版本。使用辅助函数:++```python+# 在迁移的 upgrade() 中:+from cubepi.checkpointer.postgres.alembic_helpers import (+ create_message_partitions_op,+ write_schema_version_op,+)++def upgrade():+ op.create_table(...) # 从 cubepi_metadata 自动生成+ op.execute(create_message_partitions_op()) # 创建 64 个哈希分区+ op.execute(write_schema_version_op()) # 记录 EXPECTED_SCHEMA_VERSION+```++两个辅助函数都返回 SQL 字符串——你需要传入 `op.execute(...)`。+`write_schema_version_op()` 是幂等的:它会删除之前 CubePi 版本的所有行,+然后插入当前版本。++当 CubePi 后续升级并提升了 `EXPECTED_SCHEMA_VERSION` 时,生成一个新的+revision,再次调用 `op.execute(write_schema_version_op())`。++## 数据模型++```+cubepi_threads+ thread_id (PK)+ parent_thread_id -- 用于 fork+ forked_at_seq -- fork 点处的序列号+ extra -- JSONB+ created_at / updated_at++cubepi_messages+ thread_id, seq -- 复合 PK;按 HASH(thread_id) 分为 64 个分区+ role -- "user" | "assistant" | "tool"+ metadata -- JSONB(通过 GIN 索引)+ payload -- bytea (msgpack)+ created_at++cubepi_schema_version+ version (PK)+```++重要属性:++- **`(thread_id, seq)` 是消息标识。** `seq` 在每线程中单调递增,+ 在 `pg_advisory_xact_lock(hashtext(thread_id))` 下分配。+ 两个对同一线程的并发写入者会干净地序列化。+- **`payload` 是 msgpack 编码的 `model.model_dump(mode="json")`。**+ CubePi 在读取时重建 Pydantic 模型。+- **`metadata` 是 JSONB,可查询。** 完整消息的 payload 内部也包含+ `metadata`,但这一列是 SQL 查询的规范视图。+- **表按 `HASH(thread_id)` 分为 64 个分区。** 跨分区均匀分布,+ 无每线程瓶颈。++## 并发++advisory lock 让同一线程上的追加操作跨进程安全:++```python+# 进程 A 和进程 B 同时追加到线程 "user-42"。+# 它们通过 pg_advisory_xact_lock 序列化,各自获得连续的 seq。+```++读取(`load`)不取锁——它们在事务内是快照一致性的。++默认连接池 `min=1, max=10` 对大多数应用足够;如果你的并发 agent 数+很高,请调大 `max_pool_size`。++## `save_extra` 语义++`save_extra` 做的是 JSONB 合并,而不是替换:++```sql+extra = cubepi_threads.extra || EXCLUDED.extra+```++所以先写 `{"foo": 1}` 再写 `{"bar": 2}` 会得到 `{"foo": 1, "bar": 2}`。+中间件可以安全地写入部分 dict 而不会丢失先前的键。++## Fork++`parent_thread_id` + `forked_at_seq` 列是为将来的 fork 支持预留的。+CubePi v0.3 尚未暴露 fork API——现在写入它们是为了保持 schema+的前向兼容性。++## 常见坑++- **`CubepiSchemaUninitialized`** —— 数据库为空或迁移未运行。+ 先执行宿主 alembic upgrade。+- **`CubepiSchemaMismatch`** —— 你升级了 cubepi 但未生成新的迁移。+ 生成一个、执行它,CubePi 就会启动。++ :::info Schema v2(HITL)++ cubepi ≥ HITL 版本将 `EXPECTED_SCHEMA_VERSION` 从 1 提升到 2,+ 并在 `cubepi_threads` 表中新增 `pending_request JSONB NULL` 列。+ 宿主 alembic upgrade 必须在提升 schema_version 行之前调用+ `add_pending_request_column_op()`(来自+ `cubepi.checkpointer.postgres.alembic_helpers`)。+ 完整的跨进程流程请参阅 [HITL 指南](../hitl)。+ :::+- **负载下连接池耗尽** —— 默认 `max_pool_size=10`。+ 如果应用的并发 agent 数超过此值,请调大。+- **`asyncpg.exceptions.UndefinedTableError` 在 `__aenter__` 外部** ——+ 表示你在 `async with` 之外使用了 checkpointer。连接池尚未连接。+ 请用 context manager 包裹。+- **混用宿主 SQLAlchemy `MetaData`** —— CubePi 自带独立的+ `MetaData` 实例,正是为了能与你的应用模型共存而不冲突。+ 不要将它们合并到你的全局 metadata 中——分别传给 Alembic。++## 另请参阅++- [SQLite 检查点](./sqlite) —— 单进程替代方案。+- [自定义后端](./custom) —— Protocol 详情。+- [配方 → Postgres + FastAPI 服务](../../recipes/postgres-fastapi)+ —— 一个可部署的 HTTP 前端 agent。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 9db51e0..575380b 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@@ -1,5 +1,6 @@---title: SQLite+description: "使用 SQLiteCheckpointer 实现轻量级单进程 agent 状态持久化。"---# SQLite 检查点diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl.mdindex 59ba577..a0f547e 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl.md@@ -1,5 +1,6 @@---title: 人机协同 (HITL)+description: "通过 confirm、approve 和 ask 三种动词为 CubePi agent 添加人机协同暂停能力。"sidebar_position: 10---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.mdnew file mode 100644index 0000000..3a2df01--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/composition.md@@ -0,0 +1,157 @@+---+title: 组合规则+description: "了解 CubePi 如何通过 per-hook 规则组合多个中间件。"+---++# 组合规则++当你传入多个中间件——`Agent(middleware=[m1, m2, m3])`——CubePi 按照+**每个 hook 各自的规则**进行组合。正确的理解方式是:每个 hook 采用+最适合其工作的组合规则,你不需要记忆 "before" 或 "after" 优先级猜测。++## 规则速览++| Hook | 规则 | 顺序重要吗? |+|---|---|---|+| `transform_context` | **链式**——每个看到上一个的输出 | 是 |+| `convert_to_llm` | **最后一个胜出** | 只有一个运行 |+| `transform_system_prompt` | **链式** | 是 |+| `before_tool_call` | **第一个 block 停止**;非 block 累积 | block 胜出;`edited_args` 最后写入者胜出;`hitl_trace` 合并 |+| `after_tool_call` | **后面覆盖前面** | 最后写入胜出 |+| `should_stop_after_turn` | **任一 True 即停止**(OR) | 否 |+| `after_model_response` | **带合并语义的链式** | 见下文 |++## `transform_context` 和 `transform_system_prompt`++链式:`m1` 的输出成为 `m2` 的输入,`m2` 的输出成为 `m3` 的输入。适用于分层转换:++```python+agent = Agent(+ middleware=[+ SlidingWindow(max_messages=20), # m1: 丢弃最旧的+ InjectSummary(), # m2: 前置摘要块+ ],+)+```++`m2` 看到的是截断后的列表。用户可见的 `agent.state.messages` 不受影响——+中间件只改变模型接收到的内容。++## `convert_to_llm`++有意采用最后胜出:这是发送前的最终转换。多个所有者会打架;只选一个。+CubePi 强制**列表中的最后一个**实现了 `convert_to_llm` 的中间件运行。++如果你发现自己需要两个 `convert_to_llm` 中间件,将它们合并为一个+(调用点组合:写一个调用两者的中间件)。++## `before_tool_call`++第一个 `block=True` 短路其余中间件。**非 block 返回累积:**+`edited_args` 向下游传播(每个中间件看到的是前一个编辑后的形式),+`hitl_trace` 跨链合并(当被覆盖时,旧键在 `_chain` 下归档)。++用于按从最严格到最宽松的顺序链式组合策略层:++```python+agent = Agent(+ middleware=[+ RateLimiter(), # 配额不足时阻止+ SafetyFilter(), # 参数危险时阻止;可能编辑+ AuditLogger(), # 永不阻止;记录用于可观测性+ ],+)+```++如果 `RateLimiter` 返回 `block=True`,`SafetyFilter` 和 `AuditLogger`+的 `before_tool_call` 不会运行。如果 `SafetyFilter` 返回+`edited_args={"cmd": "rm /tmp/foo"}`,工具将使用编辑后的参数运行,+`AuditLogger` 通过重建的 `ctx.args` 看到它们。+`AuditLogger.after_tool_call` 仍然触发,因为那是另一个 hook。++## `after_tool_call`++每个中间件可以返回一个设置了部分字段的 `AfterToolCallResult`;+CubePi 合并它们,后面的结果在非 `None` 字段上覆盖前面的。完整结果:++```python+class AfterToolCallResult(BaseModel):+ content: list[Content] | None = None+ details: Any = None+ is_error: bool | None = None+ terminate: bool | None = None+```++模式:早期中间件添加丰富的 `details`,后期中间件为模型净化 `content`。+两者都运行;合并后的结果组合了一个的 `details` 和另一个的脱敏 `content`。++## `should_stop_after_turn`++任一中间件返回 `True` 即结束运行。链中其余中间件不会被执行。++```python+agent = Agent(+ middleware=[+ MaxTurns(10),+ BudgetCap(usd=0.5),+ FinalAnswerSentinel(), # 当 assistant 说 "FINAL ANSWER" 时停止+ ],+)+```++## `after_model_response`++带结构化合并的链式。每个中间件看到**当前的 response**(可能已被前面的+中间件替换),并返回一个 `TurnAction`:++- `response: AssistantMessage | None` —— 若非 None,则替换当前的 response+ 供下游中间件和循环最终持久化使用。+- `inject_messages: list[Message]` —— 跨整个链追加到单个列表中,+ 然后在下一轮之前添加到上下文中。+- `decision: "natural" | "stop" | "loop_to_model"` —— **最后一个中间件的值胜出**。++```python+agent = Agent(+ middleware=[+ ProfanityRedactor(), # 重写 response+ StructuredOutputValidator(), # 可能返回 decision="loop_to_model"+ EventLogger(), # 不改变 decision+ ],+)+```++如果 `StructuredOutputValidator` 返回 `decision="loop_to_model"` 而+`EventLogger` 返回 `decision="natural"`,循环看到的是 `"natural"`——+因为最后胜出。如果这不是你想要的,请重新排序。++## 混合中间件与构造函数可调用对象++`Agent(...)` 也接受显式的 hook 可调用对象(`convert_to_llm=…`、+`before_tool_call=…` 等)。当两者都存在时,**显式可调用对象胜出**:++```python+agent = Agent(+ middleware=[LoggingMiddleware()],+ before_tool_call=my_explicit_hook, # 覆盖中间件版本+)+```++一次性 hook 使用显式形式;当行为是一个连贯的包时使用中间件类。++## 关于 `Middleware` 基类的说明++基类 `Middleware` 中未实现的方法会抛出 `NotImplementedError`。+`compose_middleware` 通过对比基方法检测到这一点,并**只连接**中间件+实际覆盖的 hook。++```python+class JustTransform(Middleware):+ async def transform_context(self, messages, *, signal=None):+ return messages[-10:]+ # 没有其他 hook。CubePi 不会调用它们。+```++## 另请参阅++- [7 个 Hook](./hooks) —— 每个 hook 的作用及触发时机。+- [示例](./examples) —— 组合在实践中的应用。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.mdnew file mode 100644index 0000000..1d6f6db--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/examples.md@@ -0,0 +1,284 @@+---+title: 示例+description: "CubePi 中间件实用示例:速率限制、重试、结构化日志、上下文截断和 HITL。"+---++# 中间件示例++针对四种最常见需求的实用中间件:速率限制、重试、结构化日志和上下文截断。++## 速率限制++当用户超过配额时阻止工具调用。将 `before_tool_call` 与外部速率限制器+(令牌桶、Redis INCR……)结合。++```python+import time+from cubepi import Middleware+from cubepi.agent.types import BeforeToolCallResult+++class RateLimitMiddleware(Middleware):+ def __init__(self, max_calls_per_min: int) -> None:+ self.max = max_calls_per_min+ self._timestamps: list[float] = []++ async def before_tool_call(self, ctx, *, signal=None):+ now = time.monotonic()+ # 丢弃超过 60 秒的记录。+ self._timestamps = [t for t in self._timestamps if now - t < 60]+ if len(self._timestamps) >= self.max:+ return BeforeToolCallResult(+ block=True,+ reason=f"Rate limit: {self.max} tool calls/min exceeded. Try again shortly.",+ )+ self._timestamps.append(now)+ return None+```++使用:++```python+agent = Agent(provider=…, model=…, middleware=[RateLimitMiddleware(max_calls_per_min=30)])+```++当达到限制时,模型会看到一个工具结果说"Rate limit exceeded…"并通常会等待或询问用户。++## 带退避的重试++在 `after_tool_call` 中重试失败的工具调用。最多 N 次,指数退避,+仅针对临时错误。++```python+import asyncio+from cubepi import Middleware+from cubepi.agent.types import AfterToolCallResult+++class RetryMiddleware(Middleware):+ def __init__(self, max_retries: int = 3, base_delay: float = 0.5) -> None:+ self.max_retries = max_retries+ self.base_delay = base_delay++ async def after_tool_call(self, ctx, *, signal=None):+ if not ctx.is_error:+ return None++ # 按名称查找工具并重新执行,最多 max_retries 次。+ tool = next(+ (t for t in (ctx.context.tools or []) if t.name == ctx.tool_call.name),+ None,+ )+ if tool is None:+ return None++ for attempt in range(1, self.max_retries + 1):+ await asyncio.sleep(self.base_delay * (2 ** (attempt - 1)))+ try:+ new_result = await tool.execute(+ ctx.tool_call.id,+ ctx.args,+ signal=signal,+ on_update=None,+ )+ return AfterToolCallResult(+ content=new_result.content,+ details={"retried": attempt, "original_error": ctx.result.content},+ is_error=False,+ )+ except Exception:+ continue++ return None # 放弃——保留原始错误+```++谨慎组合:重试非幂等工具(写入、发送、删除)可能造成实际损害。+将这类工具标记为 `execution_mode="sequential"` 并基于 `ctx.tool_call.name` 跳过。++## 结构化日志++记录每一次工具调用及其参数、时长和结果。将 `before_tool_call`(记录开始时间)+与 `after_tool_call`(记录结果)配对。将开始时间存储在 `ctx.context.extra` 中。++```python+import time, logging+from cubepi import Middleware++log = logging.getLogger("cubepi.tools")+++class ToolLoggingMiddleware(Middleware):+ async def before_tool_call(self, ctx, *, signal=None):+ ctx.context.extra.setdefault("_tool_starts", {})[ctx.tool_call.id] = time.monotonic()+ return None++ async def after_tool_call(self, ctx, *, signal=None):+ started = ctx.context.extra.get("_tool_starts", {}).pop(ctx.tool_call.id, None)+ duration_ms = int((time.monotonic() - started) * 1000) if started else None+ log.info(+ "tool_call",+ extra={+ "tool_name": ctx.tool_call.name,+ "args": ctx.args.model_dump() if hasattr(ctx.args, "model_dump") else ctx.args,+ "is_error": ctx.is_error,+ "duration_ms": duration_ms,+ },+ )+ return None+```++`ctx.context.extra` 是存储每次运行状态的最佳位置,因为:++- 其他中间件可通过同一个 `ctx.context` 看到。+- Checkpointer 在 `agent_end` 时通过 `save_extra` 持久化。+- 新对话开始时(新的 `thread_id`)会自动重置。++## 滑动窗口截断++通过仅保留最近的 N 条消息(加上 system prompt)来保持模型上下文边界:++```python+from cubepi import Middleware+++class SlidingWindow(Middleware):+ def __init__(self, max_messages: int = 20) -> None:+ self.max_messages = max_messages++ async def transform_context(self, messages, *, signal=None):+ if len(messages) <= self.max_messages:+ return messages+ return messages[-self.max_messages:]+```++`transform_context` 不接触 `agent.state.messages`——用户仍然看到完整历史。+模型只看到最后 N 条。++与注入被丢弃内容摘要的 `transform_system_prompt` 配合效果很好:++```python+class SummaryInjector(Middleware):+ async def transform_system_prompt(self, system_prompt, *, signal=None):+ summary = "Earlier in this conversation we discussed: …"+ return f"{system_prompt}\n\nContext: {summary}".strip()+```++## 最大轮次 / 预算上限++在达到最大轮次数或成本上限时硬停止 agent:++```python+class MaxTurns(Middleware):+ def __init__(self, max_turns: int) -> None:+ self.max_turns = max_turns+ self.turns = 0++ async def should_stop_after_turn(self, ctx):+ self.turns += 1+ return self.turns >= self.max_turns+++class BudgetCap(Middleware):+ def __init__(self, usd: float, model_cost) -> None:+ self.cap = usd+ self.cost = model_cost # cubepi.providers.ModelCost 或类似+ self.spent = 0.0++ async def should_stop_after_turn(self, ctx):+ m = ctx.message+ if m.usage:+ self.spent += (+ (m.usage.input_tokens / 1_000_000) * self.cost.input+ + (m.usage.output_tokens / 1_000_000) * self.cost.output+ )+ return self.spent >= self.cap+```++## 用 `after_model_response` 实现结构化输出++验证 JSON 输出,如果解析失败则重新提示:++```python+import json+from cubepi import Middleware+from cubepi.middleware.base import TurnAction+from cubepi.providers.base import TextContent, UserMessage+++class JSONOutputValidator(Middleware):+ def __init__(self, schema_cls) -> None:+ self.schema = schema_cls++ async def after_model_response(self, response, ctx, *, signal=None):+ text = "".join(+ c.text for c in response.content if isinstance(c, TextContent)+ )+ try:+ obj = json.loads(text)+ self.schema.model_validate(obj)+ return None # 有效——正常进行+ except Exception as e:+ return TurnAction(+ inject_messages=[+ UserMessage(content=[TextContent(text=f"Invalid output: {e}. Return valid JSON.")]),+ ],+ decision="loop_to_model",+ )+```++Agent 将跳过工具执行,并立即用上下文中的反馈消息重新提示模型。++## 人机协同工具确认++cubepi 在 `cubepi.hitl` 中内置了两个 HITL 中间件:++**`ConfirmToolCallMiddleware`** —— "对此工具始终询问人类":++```python+from cubepi.hitl import ConfirmToolCallMiddleware, InMemoryChannel++channel = InMemoryChannel()+agent = Agent(+ provider=…, model=…,+ middleware=[+ ConfirmToolCallMiddleware(+ channel,+ require_confirm={"bash", "write_file"},+ ),+ ],+)+```++Agent 在每次 `bash` 或 `write_file` 调用时暂停,等待宿主调用+`channel.answer(qid, ApproveAnswer(decision="approve"))`。结果驱动工具:+`approve` 执行,`deny` 带原因阻止,`edit` 重新校验并运行编辑后的参数。++**`ApprovalPolicyMiddleware`** —— 适用于通过策略引擎对工具调用进行分类的宿主:++```python+from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny++def my_policy(ctx):+ if ctx.tool_call.name in ("read_file", "grep"):+ return Approve()+ if ctx.tool_call.name.startswith("dangerous_"):+ return Deny(reason="blocked")+ return AskUser(timeout_seconds=180)++agent = Agent(+ provider=…, model=…,+ middleware=[ApprovalPolicyMiddleware(channel, policy=my_policy)],+)+```++`Deny` 完全跳过 channel(硬阻止)。`AskUser` 触发 channel 的 approve 流程。+`Approve` 立即返回。++完整细节——超时语义、编辑语义、事件、追踪 span、跨进程挂起/恢复——+请参见 [HITL 指南](../hitl)。++## 另请参阅++- [7 个 Hook](./hooks) —— 每个 hook 的精确语义。+- [组合规则](./composition) —— 多个中间件如何组合。+- [配方](../../recipes/weather-agent) —— 中间件在真实应用中的组合。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.mdnew file mode 100644index 0000000..481af03--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/hooks.md@@ -0,0 +1,190 @@+---+title: 7 个 Hook+description: "CubePi 的 7 个中间件 hook 参考——transform_context、before_tool_call、after_tool_call 等。"+---++# 7 个 Hook++`Middleware` 是一个最多包含七个可选异步方法的类。每个 hook 在 agent+循环中的精确位置触发。只实现你需要的——CubePi 只会连接你重写了的方法。++```python+from cubepi import Middleware++class MyMiddleware(Middleware):+ async def transform_context(self, messages, *, signal=None):+ ...+```++将实例传入 `Agent(middleware=[MyMiddleware(), …])`。++## `transform_context`++```python+async def transform_context(self, messages: list[Message], *, signal=None) -> list[Message]:+ ...+```++**每次调用模型之前**触发,作用于完整的消息列表。用于:++- 截断或总结以适配上下文窗口。+- 注入系统提醒(更好用 `transform_system_prompt`)。+- 动态添加或删除特定消息。++返回(可能是新的)列表。**不要修改输入**——返回一个新列表以免其他持有原引用的代码感到意外。++组合方式:链式——每个中间件看到上一个的输出。++## `convert_to_llm`++```python+async def convert_to_llm(self, messages: list[Message]) -> list[Message]:+ ...+```++**在序列化给 provider 之前**触发。这是调整 LLM 看到的最终内容的最后机会。用于:++- 将工具结果精简为纯文本。+- 为非多模态 provider 将图片内容替换为文字描述。+- 压缩较长的工具输出。++组合方式:**最后一个实现胜出**(非链式)。当多个中间件可能冲突而你希望只有一个所有者时使用。++## `transform_system_prompt`++```python+async def transform_system_prompt(self, system_prompt: str, *, signal=None) -> str:+ ...+```++**每次调用模型之前**触发,作用于 system prompt 字符串。用于:++- 注入运行时信息(当前时间、用户角色)。+- 组合模块化的 system prompt 片段。+- A/B 测试 prompt 变体。++组合方式:链式。++## `before_tool_call`++```python+async def before_tool_call(self, ctx: BeforeToolCallContext, *, signal=None) -> BeforeToolCallResult | None:+ ...+```++**每个工具调用时**触发,在参数校验之后、`tool.execute` 之前。+context 提供:++- `ctx.assistant_message` —— 发起调用的消息。+- `ctx.tool_call` —— `ToolCall` 块。+- `ctx.args` —— *校验后的* Pydantic 实例。+- `ctx.context` —— 完整的 `AgentContext`。++返回 `BeforeToolCallResult(block=True, reason="…")` 以短路——+CubePi 会将该原因作为工具结果返回,并标记 `is_error=True`。+返回 `None`(或无返回)则继续执行。++用于:权限控制、速率限制、dry-run 模式、沙箱、+人机协同确认(参见 [HITL 指南](../hitl))。++组合方式:**第一个 `block=True` 短路**整个链。++## `after_tool_call`++```python+async def after_tool_call(self, ctx: AfterToolCallContext, *, signal=None) -> AfterToolCallResult | None:+ ...+```++**每个工具调用时**触发,在 `tool.execute` 返回(或抛出异常)之后。+context 额外提供:++- `ctx.result` —— execute 返回的 `AgentToolResult`。+- `ctx.is_error` —— 工具是否出错。++返回 `AfterToolCallResult(content=…, details=…, is_error=…, terminate=…)`+以覆盖结果的单个字段(任何 `None` 字段保持原值)。返回 `None` 则原样通过。++用于:编辑、重试、日志记录、结果转换。++组合方式:后面的覆盖前面的(返回值中的每个非 `None` 字段覆盖前一个值)。++## `should_stop_after_turn`++```python+async def should_stop_after_turn(self, ctx: ShouldStopAfterTurnContext) -> bool:+ ...+```++**在每个轮次边界**触发(任何工具批次之后)。返回 `True` 以结束本次运行,+不进行下一次模型调用。++用于:最大轮次限制、预算上限、应用定义的停止条件。++组合方式:**任意一个返回 `True` 即停止**(逻辑 OR 跨链)。++## `after_model_response`++```python+async def after_model_response(+ self,+ response: AssistantMessage,+ ctx: AgentContext,+ *,+ signal=None,+) -> TurnAction | None:+ ...+```++**在 assistant 消息落定后立即**触发,在 `message_end` 发出**之前**、+在任何工具调用分发**之前**。该 hook 返回一个 `TurnAction`:++```python+from cubepi.middleware.base import TurnAction+from cubepi.providers.base import UserMessage, TextContent++TurnAction(+ response=modified_message, # 替换消息;None 则保留原消息+ inject_messages=[UserMessage(...)], # 在下一轮之前追加的额外消息+ decision="natural", # "natural" | "stop" | "loop_to_model"+)+```++三个控制流旋钮:++- `decision="natural"`(默认)—— 正常进入工具执行 / 下一轮。+- `decision="stop"` —— 在发出 `turn_end` 和 `agent_end` 后结束运行。+ 不执行工具,不再调用模型。+- `decision="loop_to_model"` —— 跳过工具执行,立即重新调用模型(配合+ `inject_messages` 使用以先添加上下文)。++用于:响应审核、带重新提示的结构化输出验证、条件路由。++组合方式:链式——每个中间件看到前一个中间件的 `response`;+`inject_messages` 跨链拼接;最后一个中间件的 `decision` 胜出。++## 中间件的构成++一个中间件不需要实现每一个 hook。只覆盖你需要的即可;基类中未实现+的 hook 会抛出 `NotImplementedError`,但 `compose_middleware` 会自动跳过它们。++```python+from cubepi import Middleware++class MaxTurnsMiddleware(Middleware):+ def __init__(self, max_turns: int) -> None:+ self.max_turns = max_turns+ self.turns = 0++ async def should_stop_after_turn(self, ctx) -> bool:+ self.turns += 1+ return self.turns >= self.max_turns+++agent = Agent(provider=…, model=…, middleware=[MaxTurnsMiddleware(5)])+```++## 另请参阅++- [组合规则](./composition) —— 多个中间件定义同一 hook 时的精确语义。+- [示例](./examples) —— 速率限制、日志、重试、滑动窗口上下文的实用中间件。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.mdindex 4e96832..82f13ed 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.md@@ -1,5 +1,6 @@---title: Anthropic+description: "通过 AnthropicProvider 在 CubePi 中使用 Claude 模型——支持思考、缓存和工具调用。"---# Anthropic Providerdiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdxindex 65991f5..da6f114 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdx+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdx@@ -1,6 +1,7 @@---id: introtitle: CubePi+description: "一个 Pythonic、异步原生的 langgraph 和 pi-agent-core 替代品。"slug: /sidebar_position: 0---@@ -9,9 +10,10 @@ import PackageVersion from '@site/src/components/PackageVersion';# CubePi-**CubePi** 是一个 Pythonic、原生异步的 Agent 框架——相对于-[langgraph](https://github.com/langchain-ai/langgraph) 等 Agent 运行时,-更精简、更易读的另一种思路。它把 Agent 建模为一个普通的 `async` 函数,+**CubePi** 是一个 Pythonic、原生异步的 Agent 框架——作为+[langgraph](https://github.com/langchain-ai/langgraph) 和+[pi-agent-core](https://github.com/anthropics/pi-agent-core) 的替代品,+更精简、更易读。它把 Agent 建模为一个普通的 `async` 函数,而不是状态图;整个核心循环你五分钟就能读完。```bashdiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/ask-user-form.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/ask-user-form.mdnew file mode 100644index 0000000..3afeb77--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/ask-user-form.md@@ -0,0 +1,184 @@+---+title: 通过 ask_user 实现多问题表单+description: "使用 CubePi 的 ask_user HITL 工具构建多问题表单以收集结构化用户输入。"+---++# 配方:通过 `ask_user` 实现多问题表单++适用场景:agent 在继续之前需要用户的**结构化答案** —— 配置向导、+偏好选择器、功能开关。++## 步骤 1:注册工具++```python+from cubepi.agent.agent import Agent+from cubepi.hitl import InMemoryChannel, ask_user_tool++channel = InMemoryChannel()++agent = Agent(+ provider=...,+ model=...,+ system_prompt=(+ "当您需要用户在选项中选择时,请使用 ask_user 工具。"+ "对于自由形式的澄清问题,直接用文本结束当前轮次——"+ "用户的下一条消息就是答案。"+ ),+ tools=[ask_user_tool(channel)],+ channel=channel,+)+```++`ask_user` 工具像其他工具一样注册。它的+`execution_mode="sequential"` 使工具批次逐一执行——+HITL 暂停不能与并行工具执行重叠。++## 步骤 2:宿主渲染表单++模型调用 `ask_user` 并传入一个问题对象列表。宿主在 channel 上收到+一个 `AskRequest` payload:++```python+async def host():+ async for req in channel.subscribe():+ if req.payload.kind == "ask":+ answers = {}+ for q in req.payload.questions:+ if q.options is None:+ # 自由文本问题+ answers[q.key] = await my_ui.text_input(q.prompt)+ elif q.multi_select:+ answers[q.key] = await my_ui.checkbox_group(+ q.prompt, [(o.label, o.value) for o in q.options],+ )+ else:+ answers[q.key] = await my_ui.radio_group(+ q.prompt,+ [(o.label, o.value) for o in q.options],+ allow_input_indexes=[+ i for i, o in enumerate(q.options) if o.allow_input+ ],+ )+ await channel.answer(req.question_id, answers)+```++## 模型看到的工具参数++模型可以传入混合了自由文本、单选和多选字段的问题:++```json+{+ "questions": [+ {+ "key": "project_type",+ "prompt": "什么类型的项目?",+ "options": [+ {"label": "Web 应用", "value": "web"},+ {"label": "CLI 工具", "value": "cli"},+ {"label": "库", "value": "lib"}+ ]+ },+ {+ "key": "framework",+ "prompt": "哪个框架?",+ "options": [+ {"label": "React", "value": "react"},+ {"label": "Vue", "value": "vue"},+ {"label": "其他", "value": "other", "allow_input": true}+ ]+ },+ {+ "key": "features",+ "prompt": "你需要哪些功能?",+ "multi_select": true,+ "options": [+ {"label": "认证", "value": "auth"},+ {"label": "支付", "value": "payments"},+ {"label": "文件上传", "value": "uploads"}+ ]+ },+ {+ "key": "project_name",+ "prompt": "这个项目叫什么名字?"+ }+ ]+}+```++## 答案结构++宿主用一个 `key → value` 的 dict 回答:++```python+# 上述表单的答案示例:+{+ "project_type": "web",+ "framework": "svelte", # 用户选择了"其他"并输入了"svelte"+ "features": ["auth", "uploads"],+ "project_name": "my-saas"+}+```++答案被填入工具结果的 `details["hitl"]["answers"]`。+模型可以通过文本内容看到人类可读的摘要,也可以通过 dict 进行结构化消费。++## 取消与超时++如果宿主通过 `channel.cancel(qid, reason)` 取消:++```python+await channel.cancel(req.question_id, reason="user closed the form")+```++工具会向模型显示一个错误结果:++```+tool_result.is_error = True+tool_result.details["hitl"]["outcome"] = "cancelled"+tool_result.details["hitl"]["reason"] = "user closed the form"+```++如果超时到期:++```+tool_result.details["hitl"]["outcome"] = "timed_out"+tool_result.details["hitl"]["seconds"] = 30.0+```++两种情况下模型都会看到干净的错误结果,并能做出相应反应——+再次提问、回退到默认值或向用户报告。++## 进程内示例(完整可运行代码段)++```python+import asyncio+from cubepi.agent.agent import Agent+from cubepi.hitl import InMemoryChannel, ask_user_tool++channel = InMemoryChannel()++agent = Agent(+ provider=...,+ model=...,+ tools=[ask_user_tool(channel)],+ channel=channel,+)++async def host():+ async for req in channel.subscribe():+ if req.payload.kind == "ask":+ answers = {+ q.key: q.options[0].value if q.options else ""+ for q in req.payload.questions+ }+ await channel.answer(req.question_id, answers)++async def main():+ host_task = asyncio.create_task(host())+ try:+ await agent.prompt("Scaffold a new project.")+ finally:+ host_task.cancel()++asyncio.run(main())+```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.mdnew file mode 100644index 0000000..a36fbbf--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/sandbox-confirm.md@@ -0,0 +1,138 @@+---+title: 使用 ApprovalPolicyMiddleware 做沙箱确认+description: "使用 CubePi 的 ApprovalPolicyMiddleware 实现沙箱工具确认——自动放行、拒绝或人工确认。"+---++# 配方:使用 `ApprovalPolicyMiddleware` 做沙箱确认++适用场景:一个 web 服务中每个工具调用都经过规则引擎,被分类为自动放行、+硬阻止或人类确认。++## 步骤 1:定义策略函数++策略接收一个 `BeforeToolCallContext` 并返回一个 `ApprovalDecision` ——+`Approve()`、`Deny(reason)` 或 `AskUser(...)`。++```python+from cubepi.hitl import Approve, AskUser, Deny++# 模拟规则引擎 —— 替换为你实际的策略目录。+def classify_command(cmd: str) -> tuple[str, str | None]:+ """(tier, reason) — "allow", "block", 或 "confirm"."""+ if cmd.startswith(("ls", "cat", "head", "grep", "find")):+ return ("allow", None)+ if "rm -rf /" in cmd or cmd.startswith("dd"):+ return ("block", "destructive I/O")+ return ("confirm", "needs human review")+++def sandbox_policy(ctx):+ cmd = ctx.args.cmd # ctx.args 是校验后的 pydantic 模型+ tier, reason = classify_command(cmd)++ if tier == "allow":+ return Approve()+ if tier == "block":+ return Deny(reason=reason or "blocked by policy")+ return AskUser(+ timeout_seconds=180,+ details={"matched_rule": tier, "impact": reason or "unknown"},+ )+```++`ctx.args` 是**校验后的 pydantic 模型**。通过属性访问字段+(`ctx.args.cmd`)。中间件内部会将其转为 dict 用于 channel 的 approve payload,+但你的策略收到的仍然是类型化的模型。++## 步骤 2:接入 agent++```python+from cubepi.agent.agent import Agent+from cubepi.checkpointer.postgres import PostgresCheckpointer+from cubepi.hitl import ApprovalPolicyMiddleware, CheckpointedChannel++async def main():+ async with PostgresCheckpointer("postgresql://...") as cp:+ channel = CheckpointedChannel(checkpointer=cp, thread_id="session-1")++ agent = Agent(+ provider=anthropic,+ model=Model(id="claude-sonnet-4-6", provider="anthropic"),+ system_prompt="You are a helpful assistant with access to a bash shell.",+ tools=[bash_tool],+ middleware=[+ ApprovalPolicyMiddleware(channel, policy=sandbox_policy),+ ],+ channel=channel,+ checkpointer=cp,+ thread_id="session-1",+ )++ await agent.prompt("list files then delete temp logs")+ # Agent 运行中;当 bash 被调用时,sandbox_policy 决定:+ # ls → Approve() → 立即执行+ # rm /tmp/logs → AskUser() → channel 挂起,HitlRequestEvent 触发+```++## 步骤 3:宿主处理挂起的请求++```python+async def host_loop(channel: CheckpointedChannel):+ async for req in channel.subscribe():+ if req.payload.kind == "approve":+ tool_name = req.payload.tool_name+ command = req.payload.args.get("cmd", "")+ details = req.payload.details or {}+ timeout = req.timeout_seconds # 前端倒计时用的秒数++ # 渲染给前端:tool_name、command、details["matched_rule"]、+ # details["impact"]、以及基于 timeout 的倒计时。+ human_answer = await my_frontend.show_confirm(+ tool_name=tool_name,+ command=command,+ details=details,+ timeout=timeout,+ )+ # 根据人类的决定构建 ApproveAnswer。+ from cubepi.hitl import ApproveAnswer+ human_answer = ApproveAnswer(+ decision=ui_response["decision"], # "approve" | "deny" | "edit"+ reason=ui_response.get("reason"), # 仅用于 deny+ edited_args=ui_response.get("edited_args"), # 仅用于 edit+ )+ await channel.answer(req.question_id, human_answer)+ elif req.payload.kind == "ask":+ await channel.answer(req.question_id, await my_frontend.show_form(req))+ else: # confirm+ await channel.answer(req.question_id, await my_frontend.show_confirm(req))+```++## 决策语义++| 人类选择 | 工具结果 | `hitl_trace["decision"]` | 模型看到 |+|---|---|---|---|+| 批准 | 使用原始参数执行 | 未设置(直通,无 HITL 细节) | 正常 `tool_result` |+| 拒绝 | 被阻止 | `"human_deny"` | `tool_result.is_error=True` 及用户的原因 |+| 编辑 | 使用编辑后的参数执行 | `"edit"` + `original_args` / `edited_args` | 正常 `tool_result`(来自编辑后的执行) |++策略决策(不经询问人类直接硬阻止)携带+`hitl_trace["decision"]="policy_deny"`。++## 超时行为++如果人类在 `timeout_seconds` 内未响应,中间件会转换为+`BeforeToolCallResult(block=True, deny_reason="approval_timeout")`。+模型看到 `tool_result.is_error=True`,其中+`details.hitl.decision="timed_out"`,并自然产生一个解释超时的后续轮次。++## 中止++如果用户关闭标签页或管理员终止对话:++```python+await agent.abort_pending(reason="user closed tab")+```++这会干净地关闭对话:为所有未解决的 tool call 追加合成的 deny tool_result,+持久化一个终止性的 `AssistantMessage(stop_reason="aborted")`,并触发+`AgentAbortedEvent`。下一次 `agent.prompt(...)` 重新开始。diff --git a/website/src/components/Home/Hero.tsx b/website/src/components/Home/Hero.tsxindex 193b1d1..7a77c50 100644--- a/website/src/components/Home/Hero.tsx+++ b/website/src/components/Home/Hero.tsx@@ -19,12 +19,12 @@ export default function Hero() {<imgclassName={styles.banner}src={social}- alt="CubePi · A Pythonic, async-native agent framework"+ alt="CubePi · A Pythonic alternative to langgraph and pi-agent-core"width={1280}height={640}/><div className={styles.eyebrow}>cubepi · v{version} · alpha</div>- <h1 className={styles.h1}>A Pythonic, async-native agent framework.</h1>+ <h1 className={styles.h1}>A Pythonic alternative to langgraph and pi-agent-core.</h1><p className={styles.lead}>Plain async functions instead of graph nodes. 3 deps. Append-only checkpointing.</p>diff --git a/website/src/components/Home/WhyTable.tsx b/website/src/components/Home/WhyTable.tsxindex 433eb9a..6827abb 100644--- a/website/src/components/Home/WhyTable.tsx+++ b/website/src/components/Home/WhyTable.tsx@@ -15,7 +15,7 @@ const ROWS: { label: string; langgraph: string; cubepi: string }[] = [export default function WhyTable() {return (<section className={styles.section}>- <h2 className={styles.h2}>Why CubePi</h2>+ <h2 className={styles.h2}>Why CubePi — a langgraph and pi-agent-core alternative</h2><div className={styles.tableWrap}><table className={styles.table}><thead>diff --git a/website/src/pages/index.tsx b/website/src/pages/index.tsxindex 2354a71..84ef87c 100644--- a/website/src/pages/index.tsx+++ b/website/src/pages/index.tsx@@ -9,8 +9,8 @@ import MetaBar from '@site/src/components/Home/MetaBar';export default function Home(): JSX.Element {return (- <Layout title="CubePi — Pythonic async-native agent framework"- description="CubePi is a Pythonic, async-native agent framework. Plain async functions, append-only checkpointing, 3 core dependencies.">+ <Layout title="CubePi — a Pythonic langgraph and pi-agent-core alternative"+ description="CubePi is a Pythonic, async-native alternative to langgraph and pi-agent-core. Plain async functions, append-only checkpointing, 3 core dependencies."><Hero /><WhyTable /><HelloAgent />diff --git a/website/static/robots.txt b/website/static/robots.txtnew file mode 100644index 0000000..4e062f4--- /dev/null+++ b/website/static/robots.txt@@ -0,0 +1,4 @@+User-agent: *+Allow: /++Sitemap: https://cubepi.pages.dev/sitemap.xml