OpenProse 会话内状态管理(In-Context State)实战指南:用叙述协议把对话历史变成 VM 工作记忆

原创2026-10-15 13:04:281,758 阅读
文章标签:人工智能大模型AI 应用后端LLM 网关即时通讯AI Agent插件系统本地部署MCP Clients

OpenProse 会话内状态管理(In-Context State)实战指南:用叙述协议把对话历史变成 VM 工作记忆

导读:本文围绕 OpenProse 的两大状态管理方案之一——会话内状态(in-context state),完整讲解其适用边界、14 类文本标记协议(Narration Protocol)、各语言构造(会话/并行/循环/异常/块调用/导入)的叙述写法、上下文序列化策略与完整执行轨迹示例。读完本文,你将能在 OpenClaw 中编写并运行 .prose 程序时,用“边说边记”的方式让 VM 在对话历史里持久化执行状态,并在程序启动时正确选择文件系统(filesystem)与会话内两种状态模式。

OpenProse 是 OpenClaw 插件体系中随 extensions/open-prose 技能包一同交付的 AI 编排语言:LLM 是模拟器,当它读到足够精确的系统描述时,不只是“描述”一个虚拟机,而是“成为”那个虚拟机——模拟保真度足够高,就等于实现。而虚拟机最重要的组成部分之一,就是执行状态如何保存。在 VM 语义文档 的组件映射中,“工作内存”对应的是对话历史,“持久存储”对应的是 .prose/ 目录。会话内状态管理走的就是前一条路。

核心思想:对话历史就是 VM 的工作内存

会话内状态(in-context state)的机制可以概括为一句话:VM 通过结构化叙述(structured narration)在对话历史中保存执行状态,VM“出声思考”,说出的话就是它记住的事。

in-context.md 开篇给出的关键原则是:

你的对话历史就是 VM 的工作内存(Your conversation history IS the VM's working memory)。

这与文件系统状态(file-based state,见 filesystem.md)形成对照:后者的原则是“目录结构即执行状态”,所有执行产物落盘到 .prose/,可检查、可续跑、可长时间运行;而会话内状态则把状态“留”在上下文窗口里,零落盘、零依赖,代价是只适合小而短的程序。

两种方式互相独立、二选一,不设计为互补关系——程序启动时就要宣布采用哪种状态模式:

OpenProse Program Start
   State mode: in-context (program is small, fits in context)

在 OpenClaw 中切换状态模式由技能入口 SKILL.md 路由:默认加载文件系统状态(state/filesystem.md);只有用户说“use in-context state”或传入 --in-context 时才加载本文对应的 state/in-context.md。

何时选择会话内状态:适用边界判定表

会话内状态不是万能的。文档给出了一张明确的判定表,先按这张表评估程序规模,再决定状态模式:

评估因素 用会话内状态(In-Context) 改用文件系统状态(File-Based)
语句数量 < 30 条语句 >= 30 条语句
并行分支 < 5 个并发 >= 5 个并发
导入程序 0-2 个导入 >= 3 个导入
嵌套深度 <= 2 层 > 2 层
预期时长 < 5 分钟 >= 5 分钟

五个维度里任何一个踩到右列,就该切到文件系统状态。这也是 SKILL.md 状态模式总表中“in-context 适用于简单程序(<30 语句)、无需持久化”的细化依据。从 postgres.md 的决策树也能看到同样的思路:<30 语句且无并行块 的程序直接走 in-context(零摩擦),否则继续评估是否需要 SQL 查询、多机协作、高并发写等能力。

叙述协议:14 类文本前缀标记

叙述协议(Narration Protocol)是会话内状态的“机器码”。每次状态变化,VM 都在自己的对话中输出一行带文本前缀标记的记录。每个状态变更都必须有标记,这是协议的硬性要求:

标记 类别 用途
[Program] 程序 程序开始、结束、定义收集
[Position] 位置 当前正在执行的语句
[Binding] 绑定 变量赋值或更新
[Input] 输入 从调用方接收输入
[Output] 输出 为调用方产出输出
[Import] 导入 拉取并调用导入的程序
[Success] 成功 会话或块完成
[Warning] 错误 失败与异常
[Parallel] 并行 进入并行、分支状态、汇合
[Loop] 循环 迭代、条件求值
[Pipeline] 管道 阶段进度
[Try] 错误处理 try/catch/finally
[Flow] 流程 条件求值结果
[Frame+] 调用栈 压栈新帧(块调用进入)
[Frame-] 调用栈 弹栈(块完成退出)

这套标记在 VM 语义文档 prose.md 的“Embodying the VM”一节也被要求:执行 .prose 程序时用叙述协议追踪状态([Position]、[Binding]、[Success] 等)。因此叙述不是可选项,而是 VM 的执行轨迹本身——VM 靠回读自己先前的消息来恢复执行状态。

按语言构造组织的叙述写法

会话内状态的价值在于“每种构造怎么叙述”都有明确范式。以下模式全部来自 in-context.md,可直接照抄进自己的叙述。

会话语句(Session Statements)

[Position] Executing: session "Research the topic"
   [Task tool call]
[Success] Session complete: "Research found that..."
[Binding] let research = <result>

对应真实程序示例:02-research-and-summarize.prose 中的 session "Research ..." 就是这类语句的原型。注意 <a href="https://link.gitcode.com/i/da3ab9e046117feed778855bdfa09c95" target="_blank">Task tool call]——在 OpenClaw 运行时映射中,上游规范里的 Task 工具对应 OpenClaw 的 sessions_spawn(见 [prose.md),每次 session 都真实派生一个子代理。

并行块(Parallel Blocks)

[Parallel] Entering parallel block (3 branches, strategy: all)
   - security: pending
   - perf: pending
   - style: pending
   [Multiple Task calls]
[Parallel] Parallel complete:
   - security = "No vulnerabilities found..."
   - perf = "Performance is acceptable..."
   - style = "Code follows conventions..."
[Binding] security, perf, style bound

这正是 16-parallel-reviews.prose 的叙述形态——三个分支 security/perf/style 并行评审后合成报告。策略 all 之外,prose.md 还定义了 first(首个完成即返回、取消其余)、any(首个成功即返回)以及失败策略 fail-fast / continue / ignore,叙述时应一并标注。

循环块(Loop Blocks)

[Loop] Starting loop until **task complete** (max: 5)

[Loop] Iteration 1 of max 5
   [Position] session "Work on task"
   [Success] Session complete
   [Loop] Evaluating: **task complete**
   [Flow] Not satisfied, continuing

[Loop] Iteration 2 of max 5
   [Position] session "Work on task"
   [Success] Session complete
   [Loop] Evaluating: **task complete**
   [Flow] Satisfied!

[Loop] Loop exited: condition satisfied at iteration 2

**...** 是 OpenProse 的“自由裁量条件”(discretion condition):不求值字面量,而是由 VM 综合此前所有会话输出做语义判断(见 prose.md)。固定循环(repeat N、for x in coll、parallel for)则见 20-fixed-loops.prose。

错误处理(Error Handling)

[Try] Entering try block
[Position] session "Risky operation"
[Warning] Session failed: connection timeout
[Binding] err = {message: "connection timeout"}
[Try] Executing catch block
[Position] session "Handle error" with context: err
[Success] Recovery complete
[Try] Executing finally block
[Position] session "Cleanup"
[Success] Cleanup complete

注意两点:失败用 <a href="https://link.gitcode.com/i/16947d370f36e8b88305e8acdd534758" target="_blank">Warning] 而非 [Error] 标记(Warning 归类于 Error 类别);catch 分支通过 context: err 把异常对象传给处理会话。真实的 try/catch/finally、嵌套重抛(throw)、以及 retry: 3 + backoff: "exponential" 的写法可对照 [22-error-handling.prose。

变量绑定(Variable Bindings)

[Binding] let research = "AI safety research covers..." (mutable)
[Binding] const config = {model: "opus"} (immutable)
[Binding] research = "Updated research..." (reassignment, was: "AI safety...")

let 可变、const 不可变、直接赋值是重绑定且要注明旧值。实践程序可参考 13-variables-and-context.prose:draft = session: writer 连续三次重赋值实现迭代精修,正是这里“reassignment, was: ...“叙述的真实场景。

输入 / 输出绑定(Input/Output Bindings)

[Input] Inputs received:
   topic = "quantum computing" (from caller)
   depth = "deep" (from caller)

[Output] output findings = "Research shows..." (will return to caller)
[Output] output sources = ["arxiv:2401.1234", ...] (will return to caller)

块调用与调用栈(Block Invocation and Call Stack)

块(block)是 OpenProse 的可复用组件,定义后可以递归调用。调用时用帧标记跟踪:

[Position] do process(data, 5)
[Frame+] Entering block: process (execution_id: 1, depth: 1)
   Arguments: chunk=data, depth=5

   [Position] session "Split into parts"
      [Task tool call]
   [Success] Session complete
   [Binding] let parts = <result> (execution_id: 1)

   [Position] do process(parts[0], 4)
   [Frame+] Entering block: process (execution_id: 2, depth: 2)
      Arguments: chunk=parts[0], depth=4
      Parent: execution_id 1

      [Position] session "Split into parts"
         [Task tool call]
      [Success] Session complete
      [Binding] let parts = <result> (execution_id: 2)  # Shadows parent's 'parts'

      ... (continues recursively)

   [Frame-] Exiting block: process (execution_id: 2)

   [Position] session "Combine results"
      [Task tool call]
   [Success] Session complete

[Frame-] Exiting block: process (execution_id: 1)

关键规则(文档原文要点):

  • 每个 [Frame+] 必须有匹配的 [Frame-]
  • execution_id 唯一标识一次调用
  • depth 表示调用栈深度(1 = 第一层)
  • 绑定携带 (execution_id: N) 表明作用域
  • 嵌套帧通过 Parent: execution_id N 串起作用域链

块定义与带参调用的真实写法(block research(topic): + do research("quantum computing")、块内再嵌套调用块、块内并行等)见 26-parameterized-blocks.prose。

作用域化绑定叙述(Scoped Binding Narration)

在块调用内部,绑定必须带上 execution_id:

[Binding] let result = "computed value" (execution_id: 43)

跨作用域解析变量时,要叙述“在哪一层找到的”:

[Binding] Resolving 'config': found in execution_id 41 (parent scope)

程序导入(Program Imports)

[Import] Importing: @alice/research
   Fetching from: https://p.prose.md/@alice/research
   Inputs expected: [topic, depth]
   Outputs provided: [findings, sources]
   Registered as: research

[Import] Invoking: research(topic: "quantum computing")
   [Input] Passing inputs:
      topic = "quantum computing"

   [... imported program execution ...]

   [Output] Received outputs:
      findings = "Quantum computing uses..."
      sources = ["arxiv:2401.1234"]

[Import] Import complete: research
[Binding] result = { findings: "...", sources: [...] }

导入由 use 语句完成(use "alice/research" as research),解析规则与远程程序一致:带协议的直接抓取、带 / 无协议的解析到 https://p.prose.md/{path}、否则视为本地文件(见 prose.md)。导入后以 research(topic: "quantum computing") 形式调用,结果可通过 result.findings、result.sources 访问,也支持解构 let { findings, sources } = research(...)。技能导入另有 import "web-search" from "github:anthropic/skills" 形式,见 11-skills-and-imports.prose。

上下文序列化:传值而非传引用

会话内状态与文件系统 / PostgreSQL 状态最本质的差别在这里:

会话内状态传递的是值(values),不是引用(references)。 绑定值直接存放在对话历史中。

因此把上下文交给后续 session 时,必须按规模选择合适的策略:

上下文大小 策略
< 2000 字符 原样传入(Pass verbatim)
2000-8000 字符 压缩为要点(Summarize to key points)
> 8000 字符 只提取核心(Extract essentials only)

序列化格式:

Context provided:
---
research: "Key findings about AI safety..."
analysis: "Risk assessment shows..."
---

明确的限制:会话内状态无法支持 RLM 风格(Recursive Language Model)的“环境即变量”模式——那种模式下代理需要查询任意大的绑定。凡程序包含大体积中间值,应改用 filesystem.md(绑定落盘到 .prose/runs/{id}/bindings/{name}.md,VM 只持有文件路径指针)或 postgres.md(绑定存入 openprose.bindings 表)。这与 prose.md 中“文件系统/数据库状态按引用传上下文”的机制形成对照——后者让 VM 上下文保持精简,中间值可以任意大。

完整执行轨迹示例

综合运用以上所有叙述模式,文档给出了一个含 agent、会话、并行、循环、上下文序列化的完整示例程序及其叙述。程序原文:

agent researcher:
  model: sonnet

let research = session: researcher
  prompt: "Research AI safety"

parallel:
  a = session "Analyze risk A"
  b = session "Analyze risk B"

loop until **analysis complete** (max: 3):
  session "Synthesize"
    context: { a, b, research }

对应叙述(完整版):

[Program] Program Start
   Collecting definitions...
   - Agent: researcher (model: sonnet)

[Position] Statement 1: let research = session: researcher
   Spawning with prompt: "Research AI safety"
   Model: sonnet
   [Task tool call]
[Success] Session complete: "AI safety research covers alignment..."
[Binding] let research = <result>

[Position] Statement 2: parallel block
[Parallel] Entering parallel (2 branches, strategy: all)
   [Task: "Analyze risk A"] [Task: "Analyze risk B"]
[Parallel] Parallel complete:
   - a = "Risk A: potential misalignment..."
   - b = "Risk B: robustness concerns..."
[Binding] a, b bound

[Position] Statement 3: loop until **analysis complete** (max: 3)
[Loop] Starting loop

[Loop] Iteration 1 of max 3
   [Position] session "Synthesize" with context: {a, b, research}
   [Task with serialized context]
   [Success] Result: "Initial synthesis shows..."
   [Loop] Evaluating: **analysis complete**
   [Flow] Not satisfied (synthesis is preliminary)

[Loop] Iteration 2 of max 3
   [Position] session "Synthesize" with context: {a, b, research}
   [Task with serialized context]
   [Success] Result: "Comprehensive analysis complete..."
   [Loop] Evaluating: **analysis complete**
   [Flow] Satisfied!

[Loop] Loop exited: condition satisfied at iteration 2

[Program] Program Complete

这个程序的三条语句在仓库示例中都能找到对应物:let x = session: agent 见 13-variables-and-context.prose,并行 + 合成见 16-parallel-reviews.prose,loop until **...** (max: N) 见 20-fixed-loops.prose。

状态类别清单:VM 必须在叙述中跟踪什么

为了能仅凭回读自己的消息恢复执行,VM 需要跟踪以下十类状态(原文档 State Categories 表):

类别 要跟踪的内容 示例
导入注册表 导入的程序与别名 research: @alice/research
Agent 注册表 全部 agent 定义 researcher: {model: sonnet, prompt: "..."}
块注册表 全部块定义(提升式 hoisted) review: {params: [topic], body: [...]}
输入绑定 从调用方接收的输入 topic = "quantum computing"
输出绑定 要返回给调用方的输出 findings = "Research shows..."
变量绑定 名称 -> 值映射(带 execution_id) result = "..." (execution_id: 3)
变量可变性 哪些是 let / const / output research: let, findings: output
执行位置 当前语句索引 Statement 3 of 7
循环状态 计数、上限、条件 Iteration 2 of max 5
并行状态 分支、结果、策略 {a: complete, b: pending}
错误状态 异常、重试次数 Retry 2 of 3, error: "timeout"
调用栈 执行帧栈 见下

调用栈状态(Call Stack State)

块调用场景下,用 [CallStack] 输出完整栈:

[CallStack] Current stack (depth: 3):
   execution_id: 5 | block: process | depth: 3 | status: executing
   execution_id: 3 | block: process | depth: 2 | status: waiting
   execution_id: 1 | block: process | depth: 1 | status: waiting

每帧跟踪四个字段:execution_id(本次调用唯一 ID)、block(块名)、depth(栈内位置)、status(executing / waiting / completed)。

与其他状态模式的取舍关系

in-context.md 明确声明:会话内状态与文件系统状态是独立的两种方案,不是互补关系。实际有四档可选,完整对比见 postgres.md 的对比表与 SKILL.md 的状态模式总表:

模式 状态位置 适用场景 状态
filesystem(默认) .prose/runs/{id}/ 文件 复杂程序、需要续跑与调试 稳定
in-context 对话历史 简单程序(<30 语句)、无需持久化 稳定
sqlite(实验性) .prose/runs/{id}/state.db 需要 SQL 查询、原子事务 实验性
postgres(实验性) PostgreSQL 数据库 真并发写、网络访问、团队协作 实验性

文件系统与 PostgreSQL 方案中,VM 只持有绑定位置指针、按引用传上下文、子代理直接写输出文件/数据库行;会话内方案则把绑定值直接写进叙述。这也是为什么会话内方案上限低(受限于上下文窗口),却最适合零摩擦跑通小程序的场景——这也是 OpenClaw 里 prose run 时最轻量的状态后端。

小结

会话内状态管理的五条要点:

  1. 用文本前缀标记跟踪每次状态变更;
  2. 状态持久化在对话历史中;
  3. 适合更小、更简单的程序(语句 <30、并行 <5、导入 ≤2、嵌套 ≤2 层、时长 <5 分钟);
  4. 要求全程一致的叙述——每个状态变化都打标记;
  5. 让状态在对话中可见——状态即叙述,叙述即状态。

叙述协议保证了 VM 只需回读自己先前发出的消息即可恢复执行状态。这就是会话内状态的全部哲学:你说出什么,你就记住什么(What you say becomes what you remember)。 在 OpenClaw 中启用 open-prose 插件(README.md 中 plugins.entries."open-prose".enabled = true 后重启 Gateway),用 prose run <file.prose> 运行小程序、在程序头宣布 State mode: in-context,即可亲手验证这套“对话即内存”的执行模型。

登录后查看全文
openclaw-zero-token