-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodegraph.html
More file actions
249 lines (226 loc) · 10.8 KB
/
Copy pathcodegraph.html
File metadata and controls
249 lines (226 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RiceAgent 项目 CodeGraph 逻辑图</title>
<style>
:root { color-scheme: dark; }
* { box-sizing: border-box; }
body {
margin: 0; padding: 32px 24px 80px;
background: #0d1117; color: #e6edf3;
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", -apple-system, sans-serif;
line-height: 1.6;
}
h1 { font-size: 26px; border-bottom: 1px solid #30363d; padding-bottom: 12px; }
h2 { font-size: 19px; margin-top: 48px; color: #875FFF; }
.sub { color: #8b949e; font-size: 14px; }
.card {
background: #161b22; border: 1px solid #30363d; border-radius: 10px;
padding: 20px; margin-top: 14px; overflow-x: auto;
}
.mermaid { display: flex; justify-content: center; }
.legend { color: #8b949e; font-size: 13px; margin-top: 8px; }
code { background:#1f242d; padding:1px 6px; border-radius:5px; font-size: 13px; color:#79c0ff; }
</style>
</head>
<body>
<h1>🐱 RiceAgent · 终端 AI 编程助手 — CodeGraph 逻辑图</h1>
<p class="sub">Python 3.11+ · Textual / Anthropic / OpenAI / MCP · 约 2.2 万行源码 · 五种运行入口 · 五层架构</p>
<h2>① 整体分层架构</h2>
<div class="card"><div class="mermaid">
flowchart TB
subgraph UI["交互层 · Interaction"]
direction LR
A1["RiceAgentApp<br/>Textual 终端 TUI"]
A2["-p 非交互模式<br/>stdout / stream-json"]
A3["RemoteServer<br/>WebSocket + 浏览器 UI"]
end
subgraph CORE["引擎层 · Engine"]
direction LR
B1["Agent<br/>ReAct 主循环"]
B2["ConversationManager<br/>历史 · token 估算"]
B3["prompts.py<br/>System / Plan 提示词"]
B4["client.py<br/>Anthropic / OpenAI / Compat"]
B5["serialization.py<br/>消息协议适配"]
end
subgraph CTX["上下文管理 · Context"]
direction LR
C1["Layer 1<br/>结果落盘 + 预览"]
C2["Layer 2<br/>auto-compact 摘要"]
C3["RecoveryState<br/>压缩后恢复"]
end
subgraph TOOL["工具层 · Tools"]
direction LR
D1["ToolRegistry<br/>注册 / 禁用 / 延迟加载"]
D2["基础工具<br/>ReadFile·WriteFile·EditFile<br/>Bash·Glob·Grep"]
D3["能力工具<br/>Agent·Task*·Team*·AskUser<br/>LoadSkill·ToolSearch 等"]
end
subgraph SEC["安全层 · Security"]
direction LR
E1["PermissionChecker<br/>五层决策链"]
E2["PathSandbox<br/>路径沙箱"]
E3["OS 沙箱<br/>bwrap / seatbelt"]
end
subgraph MEM["记忆层 · Memory"]
direction LR
F1["MemoryManager<br/>.md + frontmatter 双目录"]
F2["Recall<br/>相关记忆选择器"]
F3["Session<br/>持久化 / 恢复"]
F4["Consolidator<br/>后台整理"]
end
subgraph MULTI["多 Agent 协作"]
direction LR
G1["AgentLoader<br/>子 Agent 定义"]
G2["TeamManager<br/>团队 / 信箱"]
G3["WorktreeManager<br/>git worktree 隔离"]
G4["TraceManager<br/>调用追踪"]
end
subgraph EXT["扩展机制"]
direction LR
H1["MCPManager<br/>外部工具接入"]
H2["HookEngine<br/>生命周期钩子"]
H3["SkillLoader<br/>技能"]
H4["CommandRegistry<br/>斜杠命令"]
end
UI --> CORE
CORE --> CTX
CORE --> TOOL
TOOL --> SEC
CORE --> MEM
TOOL --> MULTI
MEM -.-> MULTI
EXT -.-> TOOL
</div></div>
<p class="legend">说明:<code>__main__.py</code> 统一入口 → 三种交互形态;核心是 <code>Agent</code> 主循环,向下驱动工具/上下文/记忆/多 Agent,横向挂接安全与扩展。</p>
<h2>② Agent ReAct 主循环(agent.py 的 run())</h2>
<div class="card"><div class="mermaid">
flowchart TB
S(["run(conversation)"]) --> ENV["注入环境上下文<br/>(cwd·os·skill·agent 目录)"]
ENV --> LTM["注入长期记忆<br/>instructions + MEMORY.md"]
LTM --> HOOK1["session_start 钩子"]
HOOK1 --> LOOP{"循环迭代"}
LOOP --> HOOK2["turn_start 钩子"]
HOOK2 --> MAIL["消费团队信箱 / 通知"]
MAIL --> SYS["构建 system prompt"]
SYS --> PLAN{"Plan 模式?"}
PLAN -->|是| PLANREM["注入 plan 提示词<br/>只读 + 写 plan 文件"]
PLAN -->|否| DEFER["提示延迟工具名<br/>(可用 ToolSearch 加载)"]
PLANREM --> DEFER
DEFER --> BUDGET["Layer1: tool-result 落盘预算"]
BUDGET --> COMPACT{"Layer2: 接近窗口上限?"}
COMPACT -->|是| SUMMARIZE["auto_compact 摘要<br/>保留近期尾部 + 熔断"]
COMPACT -->|否| STREAM
SUMMARIZE --> STREAM
STREAM["流式调用 LLM<br/>StreamCollector 解析事件"]
STREAM --> ONTOOL{"收到 ToolUseEvent?"}
ONTOOL -->|是| PERM{"权限检查 → 需要 ask?"}
PERM -->|是| DEFERED["延迟到流结束<br/>顺序执行(可交互)"]
PERM -->|否| EXEC["StreamingExecutor<br/>立即并发执行工具"]
ONTOOL -->|否| NOCALL
STREAM --> MAXTOK{"stop_reason=max_tokens?"}
MAXTOK -->|是| RETRY["提升输出上限 / 续写重试"]
RETRY --> LOOP
MAXTOK -->|否| NOCALL{"有 tool_calls?"}
NOCALL -->|否| DONE["写 assistant 消息<br/>触发记忆提取·整理<br/>turn_end/session_end 钩子"]
DONE --> LOOPDONE(["yield LoopComplete<br/>结束"])
NOCALL -->|是| ADDASS["写 assistant 消息(含 tool_uses)<br/>锚定真实 token 用量"]
ADDASS --> COLLECT["收集流式工具结果"]
COLLECT --> EXECDEF["执行延迟(需确认)工具"]
EXECDEF --> UNKNOWN{"连续未知工具≥3?"}
UNKNOWN -->|是| ERR(["ErrorEvent 终止"])
UNKNOWN -->|否| ADDRES["写 tool_results 消息"]
ADDRES --> RECALL["注入非阻塞记忆召回结果"]
RECALL --> EXITPLAN{"调用了 ExitPlanMode?"}
EXITPLAN -->|是| LOOPDONE
EXITPLAN -->|否| TURN["turn_end 钩子<br/>yield TurnComplete"]
TURN --> LOOP
</div></div>
<p class="legend">关键点:工具在 LLM 流式输出期间就开始执行(<code>StreamingExecutor</code>);需确认的工具延迟到流结束后顺序执行;token 用量用「真实 API 锚点 + 尾部字符估算」混合计算。</p>
<h2>③ 权限五层防护(permissions/checker.py 的 check())</h2>
<div class="card"><div class="mermaid">
flowchart TB
Q(["工具调用 check(tool, args)"]) --> L0{"L0 Plan 模式例外?"}
L0 -->|允许白名单| ALLOW(["allow"])
L0 -->|否| L1{"L1 安全只读命令?"}
L1 -->|是| ALLOW
L1 -->|否| L1B{"L1b 危险命令黑名单?"}
L1B -->|命中 rm -rf/格式化等| DENY(["deny 拦截"])
L1B -->|否| L1C{"L1c OS 沙箱开启?"}
L1C -->|是| ALLOW
L1C -->|否| L2{"L2 路径沙箱越界?"}
L2 -->|越界| ASK1(["ask 人工确认"])
L2 -->|否| L3{"L3 规则引擎匹配?"}
L3 -->|allow| ALLOW
L3 -->|deny| DENY
L3 -->|无规则| L4B{"L4b 会话级放行?"}
L4B -->|是| ALLOW
L4B -->|否| L4["L4 权限模式矩阵兜底<br/>default/acceptEdits/plan/bypass"]
L4 --> ALLOW2(["allow / deny 按模式"])
L4 --> ASK2(["ask 人工确认"])
ASK1 --> HITL["HITL 弹窗<br/>allow/deny/allowAlways"]
ASK2 --> HITL
HITL -->|allowAlways| RULE["写本地规则 + 会话放行<br/>后续自动放行"]
</div></div>
<p class="legend">对应简历「命令拦截 + 路径沙箱 + 规则引擎 + 工具权限控制 + 人工确认」五层纵深防护。规则文件:<code>~/.riceagent/permissions.yaml</code> / <code>.riceagent/permissions.{yaml,local.yaml}</code>。</p>
<h2>④ 上下文管理两层(context/manager.py)</h2>
<div class="card"><div class="mermaid">
flowchart LR
subgraph L1["Layer 1 · 超大工具结果落盘"]
direction TB
B1["单条 > 50K 字符<br/>或聚合 > 200K 字符"] --> B2["内容写盘<br/>.riceagent/session/tool-results/"]
B2 --> B3["对话内替换为 2KB 预览<br/>+ persisted-output 标签"]
B3 --> B4["ContentReplacementState<br/>决策冻结 · 记录持久化"]
end
subgraph L2["Layer 2 · auto-compact 摘要"]
direction TB
C1["软阈值 window−13K<br/>硬阈值 window−3K"] --> C2["熔断器<br/>连续失败3次熔断"]
C2 --> C3["保留近期尾部原文<br/>tool_use/result 不拆散"]
C3 --> C4["LLM 生成前缀摘要<br/>+ RecoveryState 附件"]
C4 --> C5["replace_history<br/>摘要 + 尾部重建"]
end
L1 --> L2
</div></div>
<p class="legend">两层协同解决「上下文膨胀」:Layer1 就地替换超大结果(缓存友好,利于 prompt-cache 命中);Layer2 接近窗口时摘要压缩,并靠 <code>RecoveryState</code>(最近读过的文件 / 已激活 skill)在压缩后重建工作上下文。</p>
<h2>⑤ 多 Agent / 团队协作</h2>
<div class="card"><div class="mermaid">
flowchart TB
AGENT["主 Agent"] --> AGENTTOOL["AgentTool(Agent)"]
AGENTTOOL -->|subagent_type| SUB["子 Agent<br/>AgentLoader 定义<br/>explore/plan/general-purpose/verification"]
AGENTTOOL -->|无 type + enable_fork| FORK["Fork 子 Agent<br/>深拷贝对话继承上下文"]
AGENTTOOL -->|isolation=worktree| WT["Worktree 隔离子 Agent"]
AGENTTOOL -->|team_name| TEAMMATE["Teammate 队友<br/>长期运行 + 独立 worktree"]
SUB --> TASK["TaskManager<br/>后台任务 + 通知队列"]
FORK --> TASK
TEAMMATE --> TASK
TASK --> NOTIFY["完成即通知主 Agent<br/>task-notification"]
NOTIFY --> AGENT
TEAMMATE --> TEAM["TeamManager<br/>team / mailbox / shared task"]
TEAM --> SPAWN["后端: 进程内 / tmux / iTerm2"]
TEAMMATE -.->|SendMessage| TEAM
AGENTTOOL --> TRACE["TraceManager<br/>父子树 + token 汇总"]
TEAM --> WORKTREE["WorktreeManager<br/>git worktree 文件隔离"]
WORKTREE --> MERGE["PR 合并 / 自动清理"]
</div></div>
<p class="legend">对应简历「主从式 Multi-Agent 协作」:主 Agent 拆解/验收,子 Agent 受控执行仅返回结果;<code>git worktree</code> 做文件级隔离避免并行写冲突;coordinator 模式走 <code>teams/coordinator.py</code> 提示词。</p>
<h2>⑥ 记忆闭环(Memory & Skill 自进化)</h2>
<div class="card"><div class="mermaid">
flowchart LR
EXEC["执行/对话"] --> EXTRACT["MemoryManager.extract<br/>LLM 提炼记忆"]
EXTRACT --> CLASS["分类路由<br/>user/feedback → 用户级<br/>project/reference → 项目级"]
CLASS --> INDEX["写 .md + frontmatter<br/>更新 MEMORY.md 索引"]
INDEX --> STORE[("~/.riceagent/memory<br/>.riceagent/memory")]
STORE --> RECALL["recall 选择器<br/>相关记忆(≤5条)"]
RECALL --> INJECT["渲染 system-reminder<br/>注入下一轮对话"]
INJECT --> EXEC
STORE --> CONSOL["Consolidator<br/>后台合并去重纠错"]
CONSOL --> STORE
</div></div>
<p class="legend">对应简历「执行→反思→提炼→分类存储→索引更新→按需复用」长期记忆闭环;另有 <code>SkillExecutor</code> 把技能以 inline/fork 两种模式注入,<code>RecoveryState</code> 记录技能调用以便压缩后恢复。</p>
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
mermaid.initialize({ startOnLoad: true, theme: 'dark', securityLevel: 'loose', flowchart: { curve: 'basis' } });
</script>
</body>
</html>