# 框架总览

一个进程级事件总线解耦各子系统：dispatcher、agent loop、工具执行、存储、协作彼此不调用对方的 UI 或广播逻辑。它们 `emit`，谁关心谁订阅。

| Lane | 行为 |
| --- | --- |
| 异步旁观 | `EventBus`：谁也拦不住正在发生的事 |
| 同步问询 | `tool_gate`：唯一能拦住工具的地方 |

## 一轮对话

1. **会话** 获取或创建 prepare_turn
2. **历史** branch_from get_branch
3. **用户消息** 运行前写入 user.prompt_submitted
4. **绑定本轮** ContextVar _current_turn_id, _store
5. **上下文与循环** prepare、压缩、agent_loop run_loop_blocking
6. **助手消息** 持久化 persist_assistant_message
7. **收尾** 用量、Git 提交 finalize_turn

- **入口**: `ChatAgent().run_turn`（生产路径），最终进入 `runtime/conversation/turn_runtime/__init__.py` 的 `_process_turn_once`。`process_user_turn` 是兼容入口。同步，便于渠道 worker 线程直接调用；内部起 asyncio loop，返回 `TurnResult`
- **用户消息**: `caller=ROOT` 的 DAG Call 节点，运行前写入，崩溃也留痕。发 `chat_ack`、`user_message` 给 UI
- **绑定本轮**: `TurnBindings` 设置 `_current_turn_id`，本轮所有协程（工具、Agent 方法、`send_message`）都读它，用来归属文件备份和子分支锚点；以及 `_store`，指向同一 DAG 的 `SessionNodeWriter`。助手 id 是 `user_msg_id + "_reply"`。成功、异常、提前返回都会 reset
- **结束**: 发 `chat_response`，返回 `TurnResult`

### 历史与分支

| `branch_from` | 历史 | 含义 |
| --- | --- | --- |
| `INHERIT_PARENT` | `db.get_branch(sid)` | 多轮：当前分支全部历史 |
| `None` | `[]` | 根级 fork：从空开始 |
| `"<node_id>"` | `db.get_branch(sid, node_id)` | 兄弟 fork：到分叉点为止 |

单轮与多轮只差链长。写入分支就是让用户节点的 caller 指向非活跃尾部（`set_head` 移动 UI 指针），或经 `agent` 工具新建根。

### 调模型前

1. `run_loop_blocking` 调 `ContextEngine.prepare(...)`：把 DAG 历史渲染成 LLM 消息（`TurnPrep`）。
2. `should_auto_compact(prep)` 为真时：`compact`（LLM 压缩成持久节点）；然后重新 prepare。
3. prompt 每个 loop 只加一次，保持 prompt 缓存前缀。
4. `agent_loop([prompt], context, config, ...)`。

### 核心循环

1. push `AgentEventTurnStart`。
2. `_stream_assistant_response` 调模型。
3. 取出 `ToolCall`，`_execute_tool_calls` 执行，结果追加回 context。
4. push `AgentEventTurnEnd`。没有工具、steering 和 follow-up 时停止。

聊天轮次没有迭代上限。`runtime.exec` 传 `max_iterations=20`。

### 每次工具调用

| 步骤 | 内容 |
| --- | --- |
| 开始 | push `AgentEventToolStart` |
| 发布 | `make_event("tool.before", ...)` 加 `emit`：同一事件服务旁观和门 |
| 门 | `decide_tool_gate`。任一 deny 即拦，理由合并；抛错的 gate 按放行 |
| 被拒 | `ToolGateDenied` 把理由作为错误结果交回模型 |
| 子 agent | 同样生效：它在 `permission_mode` 包装之外，`bypass` 关不掉 |
| 执行 | `tool.execute(...)`，前后做 cwd 快照和文件 checkpoint |
| 结束 | push `AgentEventToolEnd`，发 `tool.after` |
| 回灌 | `ToolResultMessage`。每个工具后检查 steering，命中则跳过剩余工具 |

### 收尾

- **失败**: 错误折进占位行或独立错误节点，`head_id` 移到失败的一轮
- **成功**: `persist_assistant_message`，然后 `finalize_turn`：更新 head 和 token；回填 ContextCommit 输出；`after_turn` 回灌 provider 用量；影子 Git 按轮提交和项目自动提交（`commit_turn_changes`）；自动标题、用量、快照淘汰；会话状态
- **DAG**: 用户节点、助手占位、工具结果和 Agent 方法节点都进同一个 `SessionNodeWriter`。`commit_turn` 把会话字段落盘：只追加，没有可变镜像文件，并发 agent 不会冲突

## 事件

| 事件 | 谁发 | 谁收 | 备注 |
| --- | --- | --- | --- |
| `user.prompt_submitted` | `turn_runtime/prep.py` | proactive 状态旁观 | 用户消息已提交 |
| `tool.before` | `agent/loop/tool_dispatch.py` | tool_gate （同步）、旁观 | 唯一拦截点 |
| `tool.after` | `agent/loop/tool_dispatch.py` | 旁观 | 带 is_error |
| `model.response_started` | `agent/loop/provider_lifecycle.py` | 旁观 | 模型流开始 |
| `model.response_completed` | `agent/loop/provider_lifecycle.py` | proactive 收尾策略 | 收尾检查 |
| `subagent.started / .ended` | `jobs/runner/shared.py` | 旁观 | origin 为 system；session 显式传递 |
| `branch.message_sent` | `send_message.py` | 旁观、ws.frame | from、to |
| `question.asked` | `agent/questions.py` | 渠道 _question_bridge.py | 同时进总线和 ws 帧 |
| `question.replied` | `permissions/approvals/lifecycle.py` | 前端 | 只走 ws 帧 |
| `question.rejected` | `agent/questions.py` | 前端、按收回处理 | 只走 ws 帧 |
| `context.compacted` | `context/engine.py` | UI、旁观 | 已压缩 |
| `file.changed` | functions watcher and others | 旁观 | 文件变更 |
| `channel.message_inbound` | channels | 旁观 | 入站消息 |
| `reminder.fired` | scheduler worker | scheduler/reminders.py | 展示并唤醒 agent |
| `memory.ingest_started / .ended` | memory | 旁观 | 记忆摄入 |
| `skills.changed, plugins.update_available, sessions.listed, branches.listed` | various | UI、旁观 | 列表与可用更新 |
| `ws.frame` | `emit_ws_frame` | interfaces/server/server.py | 透传；来源不直接碰 _broadcast |

路径默认在 `openprogram/runtime/` 下。订阅方：proactive 引擎订全部事件再按 `on` 过滤；Web 服务只订 `ws.frame`；渠道桥只订 `question.asked`。`emit` 是 fire-and-forget：handler 抛错打到 stderr，绝不影响发射方；没有 loop 的 async handler 被跳过；`emit_safe` 吞掉一切异常。

## 分层

| 层 | 文件 |
| --- | --- |
| 存储 | `state/store/session/session_store/`、`memory_index.py`、`session_log.py` |
| 事件层 | `runtime/events/`（`bus.py`、`tool_gate.py`）、`runtime/agent/questions.py` |
| 上下文引擎 | `runtime/context/`：`engine.py`、`render.py`、`compaction/`；finalize 在 `conversation/turn_runtime/finalize.py` |
| Agent 运行 | `runtime/agent/loop/`、`conversation/peer_agents/sub_agent_run.py`、`models/providers/utils/streams/event_stream.py`、`extensions/gating.py` |
| 协作 | `programs/tools/agents/send_message/`、`programs/tools/agents/agent/` |

### 存储

- **日志**: 每会话一份追加日志；`_open(sid)` 返回 `(SessionLog, SessionMemoryIndex)`，LRU 缓存，索引可从日志重建
- **分支**: 稳定分支身份加当前消息位置。`get_branch(sid[, head])` 沿 predecessor 链回走；Rewind 后不同分支引用可以停在同一位置。每个引用保留独立配置，项目文件仍共享
- **提交**: 轮次边界 `commit_turn(sid, msg)`。事件：`sessions.listed`、`branches.listed`

### 事件层

- **总线**: `EventBus.subscribe(handler, types=...)`、旧的 `on`、进程单例 `get_event_bus()`
- **Gate**: `register_tool_gate`、`decide_tool_gate`：取最严，fail-open，必须快（不许调 LLM 或慢 IO）
- **问询**: `QuestionRegistry`：进程级待答表，只认领一次，线程安全

### 上下文引擎

- **工具输出**: 工具结果在生成时按权重截一次，之后每个请求按存下的样子完整发送；只有压缩会替换旧轮次
- **上下文 commit**: `state/store/session/context_commit/`：每轮的存档记录，分支合并时写入，显示在上下文时间线（`context/commit/views.py`）。finalize 回填最终助手输出
- **事件**: `context.compacted`

### Agent 运行

- **`EventStream`**: async-iterable 加终值；provider dict 事件转成 typed
- **`LoopDriver`**: `prompt`、`follow_up`（收尾时追加）
- **静态准入**: `gate(name, disabled, allowed, categories)`：fnmatch，按此顺序。`agent.json` 声明谁能用什么；和 `tool_gate` 是两回事
- **子 agent**: `run_agent_turn(sid, prompt, agent_id, ...)` 以 `source="agent_spawn"` 持久接纳一轮，继承父级权限模式和规则，并等待其 Job。返回 `AgentTurnResult`（`head_id` 是新分支 tip）；`label` 命名分支

### 协作

- **`to`**: `SID:HEAD`（从该 head 再跑一轮）或分支名。建分支归 `agent` 工具；`to="new"` 报错并指向它
- **父锚点**: `_resolve_parent` 读 session、turn ContextVar，turn id 缺失时回退到 session head：worker 线程的 ContextVar 不可靠，`subagent.started`、`.ended` 也因此显式传 session
- **投递**: 一律经 Job runner 异步（`run_agent_turn_async`）。完成时写 attach pointer，并把 follow-up 派回发起方。调用方模型把它读成 user 角色报告（`_attach_report`）：名字、任务、最终回复和 `read_conversation(session_id, head_id)`。同步 spawn 不重复，`agent` 结果里已有回复和 `SID:HEAD`
- **防护**: `agent.max_messages`（默认 0，即关闭；子继承 count + 1；A↔B 来回也计入）；一轮不能给自己发消息；目标会话必须存在；`tool.before` 同样生效
- **聊天显示**: 发送方显示工具自己那一行（“已发给 …”）；收件分支按 `[message from SID:HEAD (sender)]` 画一行，写明发送方

## 已知边界

| 范围 | 边界 |
| --- | --- |
| 插件钩子 | `tool.before` 只能观察和拒绝，不能修改，也不能由插件否决。 |
| 审批 | `Gate.ask` 尚未接审批注册表。critical fail-closed 分级等待规则层。 |
| 测试 | `process_user_turn`、`agent_loop` 若干路径没有覆盖测试。 |
| 上下文引擎 | `ContextEngine.after_turn` 在抽象基类是桩，具体引擎上才真正工作。 |

[框架对比](https://fzkuji.github.io/OpenProgram/docs/reference/design/framework-comparison/overview.zh.html)
