braid-coding-agent 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- braid_coding_agent/__init__.py +13 -0
- braid_coding_agent/assembly.py +460 -0
- braid_coding_agent/cancellation.py +25 -0
- braid_coding_agent/checkpoint/__init__.py +106 -0
- braid_coding_agent/checkpoint/git.py +305 -0
- braid_coding_agent/checkpoint/settings.py +26 -0
- braid_coding_agent/checkpoint/store.py +1261 -0
- braid_coding_agent/checkpoint/workspace.py +220 -0
- braid_coding_agent/cli.py +2168 -0
- braid_coding_agent/commands/__init__.py +50 -0
- braid_coding_agent/commands/auth.py +161 -0
- braid_coding_agent/commands/config.py +180 -0
- braid_coding_agent/commands/doctor.py +511 -0
- braid_coding_agent/commands/mcp.py +928 -0
- braid_coding_agent/commands/models.py +95 -0
- braid_coding_agent/commands/setup.py +89 -0
- braid_coding_agent/commands/uninstall.py +277 -0
- braid_coding_agent/commands/upgrade.py +381 -0
- braid_coding_agent/compaction/__init__.py +174 -0
- braid_coding_agent/compaction/prepare.py +430 -0
- braid_coding_agent/compaction/summarize.py +542 -0
- braid_coding_agent/compaction/tokens.py +204 -0
- braid_coding_agent/compaction/tool_results.py +196 -0
- braid_coding_agent/compaction/utils.py +181 -0
- braid_coding_agent/config.py +2776 -0
- braid_coding_agent/config_files.py +191 -0
- braid_coding_agent/credentials.py +252 -0
- braid_coding_agent/discovery.py +415 -0
- braid_coding_agent/extensions/__init__.py +77 -0
- braid_coding_agent/extensions/api.py +480 -0
- braid_coding_agent/extensions/runner.py +553 -0
- braid_coding_agent/formatting/__init__.py +62 -0
- braid_coding_agent/formatting/settings.py +87 -0
- braid_coding_agent/formatting/tool.py +179 -0
- braid_coding_agent/lsp/__init__.py +105 -0
- braid_coding_agent/lsp/client.py +546 -0
- braid_coding_agent/lsp/manager.py +187 -0
- braid_coding_agent/lsp/model.py +316 -0
- braid_coding_agent/lsp/protocol.py +105 -0
- braid_coding_agent/lsp/settings.py +120 -0
- braid_coding_agent/lsp/tool.py +429 -0
- braid_coding_agent/mcp/__init__.py +101 -0
- braid_coding_agent/mcp/cache.py +230 -0
- braid_coding_agent/mcp/catalog.py +108 -0
- braid_coding_agent/mcp/config.py +664 -0
- braid_coding_agent/mcp/config_store.py +142 -0
- braid_coding_agent/mcp/inspector.py +85 -0
- braid_coding_agent/mcp/panel.py +254 -0
- braid_coding_agent/mcp/runtime.py +1060 -0
- braid_coding_agent/mcp/tools.py +579 -0
- braid_coding_agent/mcp/trust.py +150 -0
- braid_coding_agent/mcp/tui_panel.py +444 -0
- braid_coding_agent/messages.py +152 -0
- braid_coding_agent/models_view.py +105 -0
- braid_coding_agent/modes/__init__.py +64 -0
- braid_coding_agent/modes/json_mode.py +480 -0
- braid_coding_agent/modes/lifecycle.py +217 -0
- braid_coding_agent/modes/print_mode.py +257 -0
- braid_coding_agent/modes/repl.py +2687 -0
- braid_coding_agent/modes/repl_commands.py +263 -0
- braid_coding_agent/modes/rpc.py +953 -0
- braid_coding_agent/modes/skill_commands.py +88 -0
- braid_coding_agent/modes/tui.py +2226 -0
- braid_coding_agent/modes/tui_control.py +90 -0
- braid_coding_agent/modes/tui_model.py +1043 -0
- braid_coding_agent/modes/tui_render.py +327 -0
- braid_coding_agent/modes/tui_rich.py +751 -0
- braid_coding_agent/modes/tui_style.py +42 -0
- braid_coding_agent/modes/wire.py +81 -0
- braid_coding_agent/netsafe.py +82 -0
- braid_coding_agent/network/__init__.py +20 -0
- braid_coding_agent/network/cache.py +77 -0
- braid_coding_agent/network/fetch.py +311 -0
- braid_coding_agent/network/html_text.py +160 -0
- braid_coding_agent/network/search.py +347 -0
- braid_coding_agent/network/settings.py +103 -0
- braid_coding_agent/network/urls.py +89 -0
- braid_coding_agent/observability/__init__.py +101 -0
- braid_coding_agent/observability/audit.py +124 -0
- braid_coding_agent/observability/collector.py +314 -0
- braid_coding_agent/observability/exporter.py +74 -0
- braid_coding_agent/observability/logging_setup.py +149 -0
- braid_coding_agent/observability/redaction.py +96 -0
- braid_coding_agent/observability/settings.py +29 -0
- braid_coding_agent/observability/spans.py +239 -0
- braid_coding_agent/permissions/__init__.py +185 -0
- braid_coding_agent/permissions/command.py +586 -0
- braid_coding_agent/permissions/engine.py +522 -0
- braid_coding_agent/permissions/evaluate.py +309 -0
- braid_coding_agent/permissions/matching.py +233 -0
- braid_coding_agent/permissions/model.py +278 -0
- braid_coding_agent/permissions/policy.py +99 -0
- braid_coding_agent/permissions/readonly.py +236 -0
- braid_coding_agent/permissions/store.py +379 -0
- braid_coding_agent/project_init.py +313 -0
- braid_coding_agent/prompt/__init__.py +98 -0
- braid_coding_agent/prompt/context_files.py +253 -0
- braid_coding_agent/prompt/project_context.py +172 -0
- braid_coding_agent/prompt/system_prompt.py +378 -0
- braid_coding_agent/questions.py +71 -0
- braid_coding_agent/render/__init__.py +56 -0
- braid_coding_agent/render/batch.py +66 -0
- braid_coding_agent/render/history.py +143 -0
- braid_coding_agent/render/stream.py +823 -0
- braid_coding_agent/render/theme.py +243 -0
- braid_coding_agent/sandbox/__init__.py +89 -0
- braid_coding_agent/sandbox/backend.py +184 -0
- braid_coding_agent/sandbox/bubblewrap.py +96 -0
- braid_coding_agent/sandbox/operations.py +301 -0
- braid_coding_agent/sandbox/policy.py +221 -0
- braid_coding_agent/sandbox/proxy.py +320 -0
- braid_coding_agent/sandbox/seatbelt.py +222 -0
- braid_coding_agent/sdk/__init__.py +31 -0
- braid_coding_agent/sdk/async_client.py +366 -0
- braid_coding_agent/sdk/client.py +386 -0
- braid_coding_agent/sdk/errors.py +52 -0
- braid_coding_agent/sdk/events.py +162 -0
- braid_coding_agent/sdk/types.py +63 -0
- braid_coding_agent/sdk/wire.py +59 -0
- braid_coding_agent/server/__init__.py +54 -0
- braid_coding_agent/server/errors.py +52 -0
- braid_coding_agent/server/http_server.py +419 -0
- braid_coding_agent/server/hub.py +530 -0
- braid_coding_agent/server/openapi.py +157 -0
- braid_coding_agent/server/registry.py +354 -0
- braid_coding_agent/server/router.py +275 -0
- braid_coding_agent/server/run.py +148 -0
- braid_coding_agent/server/schema.py +194 -0
- braid_coding_agent/server/service.py +975 -0
- braid_coding_agent/session/__init__.py +293 -0
- braid_coding_agent/session/agent_session.py +2706 -0
- braid_coding_agent/session/context_breakdown.py +302 -0
- braid_coding_agent/session/discovery.py +212 -0
- braid_coding_agent/session/entries.py +809 -0
- braid_coding_agent/session/evidence.py +295 -0
- braid_coding_agent/session/lock.py +176 -0
- braid_coding_agent/session/manager.py +1185 -0
- braid_coding_agent/session/plan.py +243 -0
- braid_coding_agent/session/plan_mode.py +423 -0
- braid_coding_agent/session/projection.py +262 -0
- braid_coding_agent/session/rewind.py +257 -0
- braid_coding_agent/session/status.py +240 -0
- braid_coding_agent/settings.py +94 -0
- braid_coding_agent/skills/__init__.py +70 -0
- braid_coding_agent/skills/loader.py +681 -0
- braid_coding_agent/startup/__init__.py +76 -0
- braid_coding_agent/startup/cache.py +72 -0
- braid_coding_agent/startup/diagnostics.py +37 -0
- braid_coding_agent/startup/monitor.py +245 -0
- braid_coding_agent/startup/phases.py +79 -0
- braid_coding_agent/startup/project.py +165 -0
- braid_coding_agent/startup/report.py +560 -0
- braid_coding_agent/startup/scheduler.py +347 -0
- braid_coding_agent/statusline.py +163 -0
- braid_coding_agent/subagents/__init__.py +22 -0
- braid_coding_agent/subagents/contract.py +75 -0
- braid_coding_agent/subagents/definitions.py +583 -0
- braid_coding_agent/subagents/registry.py +277 -0
- braid_coding_agent/subagents/runtime.py +610 -0
- braid_coding_agent/subagents/settings.py +156 -0
- braid_coding_agent/subagents/worktree.py +63 -0
- braid_coding_agent/tools/__init__.py +327 -0
- braid_coding_agent/tools/args.py +87 -0
- braid_coding_agent/tools/bash.py +359 -0
- braid_coding_agent/tools/edit.py +298 -0
- braid_coding_agent/tools/edit_diff.py +344 -0
- braid_coding_agent/tools/find.py +158 -0
- braid_coding_agent/tools/grep.py +305 -0
- braid_coding_agent/tools/ignore.py +198 -0
- braid_coding_agent/tools/ls.py +127 -0
- braid_coding_agent/tools/mutation_queue.py +90 -0
- braid_coding_agent/tools/operations.py +274 -0
- braid_coding_agent/tools/output_accumulator.py +282 -0
- braid_coding_agent/tools/output_store.py +244 -0
- braid_coding_agent/tools/path_utils.py +91 -0
- braid_coding_agent/tools/plan.py +141 -0
- braid_coding_agent/tools/prompt_notes.py +52 -0
- braid_coding_agent/tools/question.py +180 -0
- braid_coding_agent/tools/read.py +223 -0
- braid_coding_agent/tools/submit_plan.py +102 -0
- braid_coding_agent/tools/truncate.py +423 -0
- braid_coding_agent/tools/write.py +100 -0
- braid_coding_agent/untrusted.py +50 -0
- braid_coding_agent/verify/__init__.py +78 -0
- braid_coding_agent/verify/runner.py +260 -0
- braid_coding_agent/verify/settings.py +64 -0
- braid_coding_agent/verify/tool.py +143 -0
- braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
- braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
- braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
- braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""计划:多步骤任务的步骤表,存成会话树上的 **custom 条目**。
|
|
2
|
+
|
|
3
|
+
## 为什么不进模型上下文
|
|
4
|
+
|
|
5
|
+
计划是**给人和给下一次会话**的东西,不是「模型必须逐字读到的上下文」。写进上下文会
|
|
6
|
+
带来两个后果:每改一次状态就多一条消息(一个五步任务至少五条),压缩时又要为它挑
|
|
7
|
+
切点。存成 ``custom`` 条目之后,投影对它返回零条消息(``session_entry_to_context_messages``),
|
|
8
|
+
它的可见面只有两处:``update_plan`` 的工具结果(模型看到的那份摘要)与
|
|
9
|
+
``PlanUpdateEvent``(界面看到的那份状态)。
|
|
10
|
+
|
|
11
|
+
## 为什么能活过压缩
|
|
12
|
+
|
|
13
|
+
``build_context_entries`` 会把压缩点之前的条目从**上下文**里摘掉,但
|
|
14
|
+
:meth:`SessionManager.get_branch` 走的是 ``parent_id`` 链,压缩条目照样挂在链上。
|
|
15
|
+
因此「上次计划是什么」不依赖上下文,只依赖树上最后一条 ``customType == "plan"``。
|
|
16
|
+
进程重启、``/resume``、压缩之后,``/plan`` 都能立刻答出同一份表。
|
|
17
|
+
|
|
18
|
+
## 为什么按"最新一条"而不是"合并所有条目"
|
|
19
|
+
|
|
20
|
+
计划是**覆盖式**的:每一步的当前状态只在最新那条里成立。合并历史条目需要一套
|
|
21
|
+
"哪条覆盖哪条"的规则,而这套规则除了让恢复逻辑变复杂之外没有收益——旧计划本来
|
|
22
|
+
就该被忘掉。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import logging
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from typing import Literal
|
|
30
|
+
|
|
31
|
+
from braid_ai.types import JsonValue
|
|
32
|
+
from braid_coding_agent.session.entries import CustomEntry
|
|
33
|
+
from braid_coding_agent.session.manager import SessionManager
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"PLAN_CUSTOM_TYPE",
|
|
39
|
+
"PLAN_STEP_STATUSES",
|
|
40
|
+
"PlanState",
|
|
41
|
+
"PlanStep",
|
|
42
|
+
"PlanStepStatus",
|
|
43
|
+
"PlanStore",
|
|
44
|
+
"plan_from_data",
|
|
45
|
+
"plan_to_wire",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
#: 会话条目里的类型标记。扩展也写 ``custom`` 条目,靠它区分命名空间。
|
|
49
|
+
PLAN_CUSTOM_TYPE = "plan"
|
|
50
|
+
|
|
51
|
+
type PlanStepStatus = Literal["pending", "in_progress", "completed"]
|
|
52
|
+
|
|
53
|
+
#: 三档状态。顺序即界面上"没做 → 在做 → 做完"的阅读顺序。
|
|
54
|
+
PLAN_STEP_STATUSES: tuple[PlanStepStatus, ...] = ("pending", "in_progress", "completed")
|
|
55
|
+
|
|
56
|
+
_MARKERS: dict[PlanStepStatus, str] = {
|
|
57
|
+
"pending": "[ ]",
|
|
58
|
+
"in_progress": "[>]",
|
|
59
|
+
"completed": "[x]",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(slots=True, frozen=True)
|
|
64
|
+
class PlanStep:
|
|
65
|
+
"""一步:一句可执行的描述 + 当前状态。"""
|
|
66
|
+
|
|
67
|
+
step: str
|
|
68
|
+
status: PlanStepStatus
|
|
69
|
+
|
|
70
|
+
def to_wire(self) -> dict[str, JsonValue]:
|
|
71
|
+
return {"step": self.step, "status": self.status}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(slots=True, frozen=True)
|
|
75
|
+
class PlanState:
|
|
76
|
+
"""某个时刻的完整计划。
|
|
77
|
+
|
|
78
|
+
``revision`` 是树上第几条计划条目(从 1 开始,0 表示从来没有过计划)。它有两个
|
|
79
|
+
用途:界面判断"这次更新和上次是不是同一版",以及``/plan`` 能说出"改过几次"。
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
steps: tuple[PlanStep, ...] = ()
|
|
83
|
+
revision: int = 0
|
|
84
|
+
updated_at: str | None = None
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def total(self) -> int:
|
|
88
|
+
return len(self.steps)
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def completed(self) -> int:
|
|
92
|
+
return sum(1 for step in self.steps if step.status == "completed")
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def current(self) -> PlanStep | None:
|
|
96
|
+
"""第一个 ``in_progress`` 的步骤。多个并行步骤时取最靠前的那个。"""
|
|
97
|
+
return next((step for step in self.steps if step.status == "in_progress"), None)
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def is_empty(self) -> bool:
|
|
101
|
+
return not self.steps
|
|
102
|
+
|
|
103
|
+
def progress_text(self) -> str:
|
|
104
|
+
"""一行进度,给状态栏用。空计划说"无计划",不显示 ``0/0``。"""
|
|
105
|
+
if self.is_empty:
|
|
106
|
+
return "无计划"
|
|
107
|
+
current = self.current
|
|
108
|
+
if current is not None:
|
|
109
|
+
return f"{self.completed}/{self.total} · 正在做:{current.step}"
|
|
110
|
+
return f"{self.completed}/{self.total} 完成"
|
|
111
|
+
|
|
112
|
+
def lines(self) -> list[str]:
|
|
113
|
+
"""逐行渲染:``[x] 1. 读认证模块``。序号从 1 开始,与模型给的顺序一致。"""
|
|
114
|
+
return [
|
|
115
|
+
f"{_MARKERS[step.status]} {index}. {step.step}"
|
|
116
|
+
for index, step in enumerate(self.steps, start=1)
|
|
117
|
+
]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def plan_to_wire(state: PlanState) -> dict[str, JsonValue]:
|
|
121
|
+
"""计划 → wire。``completed``/``total`` 冗余给出:客户端不必自己数。"""
|
|
122
|
+
return {
|
|
123
|
+
"steps": [step.to_wire() for step in state.steps],
|
|
124
|
+
"revision": state.revision,
|
|
125
|
+
"total": state.total,
|
|
126
|
+
"completed": state.completed,
|
|
127
|
+
"updatedAt": state.updated_at,
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def plan_from_data(data: JsonValue, *, revision: int) -> PlanState:
|
|
132
|
+
"""``custom`` 条目的 ``data`` → 计划状态。形状不对抛 :class:`ValueError`。
|
|
133
|
+
|
|
134
|
+
``updatedAt`` 由调用方从条目时间戳补齐,这里只解析步骤:条目时间戳属于条目,
|
|
135
|
+
不属于 payload,两处都存会在手工改过文件之后互相矛盾。
|
|
136
|
+
"""
|
|
137
|
+
if not isinstance(data, dict):
|
|
138
|
+
raise ValueError("计划条目必须是对象")
|
|
139
|
+
raw_steps = data.get("steps")
|
|
140
|
+
if not isinstance(raw_steps, list):
|
|
141
|
+
raise ValueError("计划条目缺少 steps 数组")
|
|
142
|
+
steps: list[PlanStep] = []
|
|
143
|
+
for index, raw in enumerate(raw_steps):
|
|
144
|
+
if not isinstance(raw, dict):
|
|
145
|
+
raise ValueError(f"计划条目第 {index + 1} 步必须是对象")
|
|
146
|
+
text = raw.get("step")
|
|
147
|
+
status = raw.get("status")
|
|
148
|
+
if not isinstance(text, str) or not text.strip():
|
|
149
|
+
raise ValueError(f"计划条目第 {index + 1} 步缺少 step 文本")
|
|
150
|
+
if status not in PLAN_STEP_STATUSES:
|
|
151
|
+
raise ValueError(f"非法的计划步骤状态: {status!r}")
|
|
152
|
+
steps.append(PlanStep(step=text.strip(), status=status))
|
|
153
|
+
return PlanState(steps=tuple(steps), revision=revision)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _normalize(steps: tuple[PlanStep, ...]) -> tuple[PlanStep, ...]:
|
|
157
|
+
"""去空白并校验。空文本与未知状态都在这里挡住,不写进会话文件。"""
|
|
158
|
+
normalized: list[PlanStep] = []
|
|
159
|
+
for index, step in enumerate(steps, start=1):
|
|
160
|
+
text = step.step.strip()
|
|
161
|
+
if not text:
|
|
162
|
+
raise ValueError(f"计划第 {index} 步的文本不能为空")
|
|
163
|
+
if step.status not in PLAN_STEP_STATUSES:
|
|
164
|
+
raise ValueError(f"非法的计划步骤状态: {step.status!r}")
|
|
165
|
+
normalized.append(PlanStep(step=text, status=step.status))
|
|
166
|
+
return tuple(normalized)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class PlanStore:
|
|
170
|
+
"""一个会话的计划状态。
|
|
171
|
+
|
|
172
|
+
与权限引擎同构:**每个会话一份**,``/clear`` 与 RPC 的 ``new_session`` 换掉会话
|
|
173
|
+
时连计划一起换掉(新会话树上本来就没有旧的 ``plan`` 条目)。
|
|
174
|
+
|
|
175
|
+
构造即恢复:读当前分支上最后一条合法 ``plan`` 条目。恢复失败时**退回更早那条**
|
|
176
|
+
而不是让会话起不来——一条写坏的条目属于历史数据,不该阻止用户继续用这个会话。
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
def __init__(self, *, session: SessionManager) -> None:
|
|
180
|
+
self._session = session
|
|
181
|
+
self._state = PlanState()
|
|
182
|
+
self._load()
|
|
183
|
+
|
|
184
|
+
@property
|
|
185
|
+
def state(self) -> PlanState:
|
|
186
|
+
return self._state
|
|
187
|
+
|
|
188
|
+
def reload(self) -> PlanState:
|
|
189
|
+
"""从当前分支重算计划(``/rewind`` 之后)。返回重算后的状态。"""
|
|
190
|
+
self._load()
|
|
191
|
+
return self._state
|
|
192
|
+
|
|
193
|
+
def update(self, steps: tuple[PlanStep, ...]) -> bool:
|
|
194
|
+
"""写入一份新计划,返回是否真的变了。
|
|
195
|
+
|
|
196
|
+
内容与当前一致时不写条目:模型常在每个回合重复提交同一份表,为它追加一条
|
|
197
|
+
一模一样的条目既浪费磁盘,也会让 ``revision`` 失去"计划改过几次"的含义。
|
|
198
|
+
"""
|
|
199
|
+
normalized = _normalize(steps)
|
|
200
|
+
if normalized == self._state.steps:
|
|
201
|
+
return False
|
|
202
|
+
payload: JsonValue = {"steps": [step.to_wire() for step in normalized]}
|
|
203
|
+
self._session.append_custom(PLAN_CUSTOM_TYPE, payload)
|
|
204
|
+
self._load()
|
|
205
|
+
return True
|
|
206
|
+
|
|
207
|
+
def summary(self) -> str:
|
|
208
|
+
"""给 ``update_plan`` 工具结果用的文本。
|
|
209
|
+
|
|
210
|
+
工具结果是模型**唯一**能看到计划的地方,所以每一条状态都要写完整:只回
|
|
211
|
+
"已更新" 等于让模型凭记忆复述步骤,它会在下一步里记错序号。
|
|
212
|
+
"""
|
|
213
|
+
state = self._state
|
|
214
|
+
if state.is_empty:
|
|
215
|
+
if state.revision == 0:
|
|
216
|
+
return "还没有计划。多步骤任务请先调用 update_plan 列出步骤。"
|
|
217
|
+
return "计划已清空(0 步)。"
|
|
218
|
+
header = f"计划({state.completed}/{state.total} 完成,第 {state.revision} 版):"
|
|
219
|
+
return "\n".join([header, *state.lines()])
|
|
220
|
+
|
|
221
|
+
# ---------------------------------------------------------------- 内部
|
|
222
|
+
|
|
223
|
+
def _load(self) -> None:
|
|
224
|
+
"""从当前分支重算状态。最新一条合法条目胜出。"""
|
|
225
|
+
revision = 0
|
|
226
|
+
state = PlanState()
|
|
227
|
+
for entry in self._session.get_branch():
|
|
228
|
+
if not isinstance(entry, CustomEntry) or entry.custom_type != PLAN_CUSTOM_TYPE:
|
|
229
|
+
continue
|
|
230
|
+
candidate_revision = revision + 1
|
|
231
|
+
try:
|
|
232
|
+
parsed = plan_from_data(entry.data, revision=candidate_revision)
|
|
233
|
+
except ValueError as exc:
|
|
234
|
+
# 不静默:坏了要留痕,但也不能让一条历史数据把会话卡死。
|
|
235
|
+
logger.warning("忽略无法解析的计划条目 %s:%s", entry.id, exc)
|
|
236
|
+
continue
|
|
237
|
+
revision = candidate_revision
|
|
238
|
+
state = PlanState(
|
|
239
|
+
steps=parsed.steps,
|
|
240
|
+
revision=candidate_revision,
|
|
241
|
+
updated_at=entry.timestamp,
|
|
242
|
+
)
|
|
243
|
+
self._state = state
|
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
"""规划模式:会话级的只读工作方式,以及它产出的实施计划。
|
|
2
|
+
|
|
3
|
+
## 与 ``plan`` 权限模式、``update_plan`` 的分工
|
|
4
|
+
|
|
5
|
+
三样东西名字里都有 plan,管的是不同的事:
|
|
6
|
+
|
|
7
|
+
- **规划模式**(本模块)决定"这一段会话怎么工作":只读探索、产出计划、等用户批准。
|
|
8
|
+
它持有状态、写会话树、控制权限模式,是 ``/plan`` 背后的对象。
|
|
9
|
+
- **``plan`` 权限模式**(``permissions/model.py``)是工具层的硬边界:拒绝一切写操作。
|
|
10
|
+
规划模式进入时把权限引擎切到它,退出时切回进入前的模式。
|
|
11
|
+
- **``update_plan``** 记录执行阶段的步骤表与进度,与规划模式无关:批准之后照样用。
|
|
12
|
+
|
|
13
|
+
## 状态为什么写在会话树上
|
|
14
|
+
|
|
15
|
+
规划模式必须活过压缩、``/resume`` 与进程重启:用户批准之前,模型不能因为上下文被
|
|
16
|
+
摘要过一次就以为自己在正常模式。``custom`` 条目是现成的持久层(与 ``plan`` 条目同一
|
|
17
|
+
机制),投影对它返回零条消息,所以它只影响"会话是什么模式",不占模型上下文。
|
|
18
|
+
|
|
19
|
+
## 谁有权批准
|
|
20
|
+
|
|
21
|
+
只有交互方给出的答案能改变状态:REPL / TUI 在回合结束时用 ``question`` 通道问一次
|
|
22
|
+
三选一,用户选"批准并开始执行"才调用 :meth:`PlanMode.approve`;RPC 与 HTTP 通过
|
|
23
|
+
``plan`` 命令的 ``approve`` 动作表达同一个意思。模型的文字输出、模型的自我判断、
|
|
24
|
+
以及"计划里写了批准"都不构成批准。权限模式的恢复也不等于授权:批准回到的是进入
|
|
25
|
+
规划模式之前的那个模式,原有规则一条都没有放宽。
|
|
26
|
+
|
|
27
|
+
审批为什么不在 ``submit_plan`` 工具里等答案:批准会切权限模式,而系统提示词里的规划
|
|
28
|
+
段落按回合计算。在一次 run 中间换模式,后面的请求会带着"当前只读"的提示词去调用已经
|
|
29
|
+
放开的权限。放在回合边界之后,提示词与权限在每一轮开始时看到的是同一个事实。
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import logging
|
|
35
|
+
from collections.abc import Awaitable, Callable
|
|
36
|
+
from dataclasses import dataclass, replace
|
|
37
|
+
from typing import TYPE_CHECKING, Literal
|
|
38
|
+
|
|
39
|
+
from braid_agent.tools import AgentTool
|
|
40
|
+
from braid_ai.types import JsonValue
|
|
41
|
+
from braid_coding_agent.permissions.model import PermissionMode
|
|
42
|
+
from braid_coding_agent.session.entries import CustomEntry
|
|
43
|
+
from braid_coding_agent.session.manager import SessionManager
|
|
44
|
+
|
|
45
|
+
if TYPE_CHECKING:
|
|
46
|
+
# 只为类型标注导入:运行期只调用引擎上的 ``settings`` 与 ``set_mode``,
|
|
47
|
+
# 不 import 具体类,避免 session 包与 permissions 包互相拖进对方的初始化。
|
|
48
|
+
from braid_coding_agent.permissions.engine import PermissionEngine
|
|
49
|
+
|
|
50
|
+
logger = logging.getLogger(__name__)
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"APPROVED_PLAN_HEADER",
|
|
54
|
+
"PLAN_APPROVAL_OPTIONS",
|
|
55
|
+
"PLAN_MODE_CUSTOM_TYPE",
|
|
56
|
+
"PLAN_MODE_INSTRUCTION",
|
|
57
|
+
"PlanMode",
|
|
58
|
+
"PlanModeReason",
|
|
59
|
+
"PlanModeState",
|
|
60
|
+
"plan_command_intent",
|
|
61
|
+
"plan_mode_from_data",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
#: 会话条目里的类型标记,与 ``plan``(步骤表)分开命名空间。
|
|
65
|
+
PLAN_MODE_CUSTOM_TYPE = "plan_mode"
|
|
66
|
+
|
|
67
|
+
#: 审批选项的固定标签。三档含义必须稳定:工具按标签判定结论,改文案等于改协议。
|
|
68
|
+
PLAN_APPROVAL_APPROVE = "批准并开始执行"
|
|
69
|
+
PLAN_APPROVAL_REVISE = "继续修改计划"
|
|
70
|
+
PLAN_APPROVAL_EXIT = "退出规划模式"
|
|
71
|
+
PLAN_APPROVAL_OPTIONS: tuple[str, ...] = (
|
|
72
|
+
PLAN_APPROVAL_APPROVE,
|
|
73
|
+
PLAN_APPROVAL_REVISE,
|
|
74
|
+
PLAN_APPROVAL_EXIT,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
#: 状态变化的来源。界面据此决定提示什么,不靠字符串比较。
|
|
78
|
+
type PlanModeReason = Literal["entered", "submitted", "approved", "revised", "left"]
|
|
79
|
+
|
|
80
|
+
#: 进入规划模式时追加到系统提示词末尾的指引。硬约束由权限引擎执行,这段文字负责
|
|
81
|
+
#: 让模型理解意图与产出形状。
|
|
82
|
+
PLAN_MODE_INSTRUCTION = """当前处于规划模式(Plan Mode),只读。
|
|
83
|
+
|
|
84
|
+
在规划模式下,你的任务是读代码、理解需求、产出一份可执行的实施计划,不做任何修改。
|
|
85
|
+
写入类工具、修改性命令以及无法确认副作用的工具都会被权限层拒绝,换工具或重试都绕不过去。
|
|
86
|
+
|
|
87
|
+
按三个阶段工作:
|
|
88
|
+
|
|
89
|
+
1. 探索。用 read / grep / find / ls / lsp 读项目结构、关键实现与测试,可以运行只读命令
|
|
90
|
+
(例如 git status、git diff、git log、ls)。能从代码里查到的事实自己查,不要问用户。
|
|
91
|
+
2. 澄清。只有当你无法从项目里得到答案、而答案会改变实现方案时,才用 question 工具提一个
|
|
92
|
+
具体问题(2-4 个选项)。不要为了凑流程提问。
|
|
93
|
+
3. 出计划。把完整计划写成 Markdown,作为 submit_plan 的 plan 参数提交。计划必须包含:
|
|
94
|
+
目标与预期行为、实现方案、涉及的模块与接口变化、实施步骤与依赖关系、边界条件与异常
|
|
95
|
+
处理、测试与验收标准、重要假设与风险。步骤要具体到另一个 Agent 能照着做。
|
|
96
|
+
|
|
97
|
+
规则:
|
|
98
|
+
|
|
99
|
+
- 每次修改计划都重新调用 submit_plan 提交完整文本,不要在回答里贴一份计划就算提交。
|
|
100
|
+
- 提交之后停下来等用户决定,不要开始实施。
|
|
101
|
+
- 用户要求直接执行时,说明当前处于规划模式,并请对方先批准计划。
|
|
102
|
+
- 用户批准后模式会自动退出,批准结论与完整计划会出现在 submit_plan 的工具结果里。
|
|
103
|
+
- 用户没有批准之前,"计划已完成"不成立,也不允许出现任何文件改动。
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
#: 已批准计划在系统提示词里的标题行。审批结论只出现在工具结果里,这条保证
|
|
107
|
+
#: 压缩、恢复之后执行阶段仍拿得到完整计划。
|
|
108
|
+
APPROVED_PLAN_HEADER = "用户已批准下列实施计划,按它执行;偏离计划之前先说明原因。"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(slots=True, frozen=True)
|
|
112
|
+
class PlanModeState:
|
|
113
|
+
"""某个时刻的规划模式状态。
|
|
114
|
+
|
|
115
|
+
``revision`` 是计划文档提交过几版(0 表示还没有提交过)。``restore_mode`` 记着
|
|
116
|
+
进入规划模式之前用户所处的权限模式:退出时恢复的就是它,不是某个"更宽松"的默认值。
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
active: bool = False
|
|
120
|
+
goal: str = ""
|
|
121
|
+
plan: str = ""
|
|
122
|
+
revision: int = 0
|
|
123
|
+
approved: bool = False
|
|
124
|
+
restore_mode: PermissionMode = "full"
|
|
125
|
+
updated_at: str | None = None
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def has_plan(self) -> bool:
|
|
129
|
+
return bool(self.plan.strip())
|
|
130
|
+
|
|
131
|
+
def to_wire(self) -> dict[str, JsonValue]:
|
|
132
|
+
"""→ wire。``hasPlan`` 冗余给出:客户端不必自己判空白。"""
|
|
133
|
+
return {
|
|
134
|
+
"active": self.active,
|
|
135
|
+
"goal": self.goal,
|
|
136
|
+
"plan": self.plan,
|
|
137
|
+
"revision": self.revision,
|
|
138
|
+
"approved": self.approved,
|
|
139
|
+
"restoreMode": self.restore_mode,
|
|
140
|
+
"updatedAt": self.updated_at,
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def plan_mode_from_data(data: JsonValue) -> PlanModeState:
|
|
145
|
+
"""``custom`` 条目的 ``data`` → 状态。形状不对抛 :class:`ValueError`。
|
|
146
|
+
|
|
147
|
+
校验只做"能不能安全地当状态用"这一层:历史条目写坏时由调用方跳过它,
|
|
148
|
+
不让一条历史数据把会话卡在无法启动的状态。
|
|
149
|
+
"""
|
|
150
|
+
if not isinstance(data, dict):
|
|
151
|
+
raise ValueError("规划模式条目必须是对象")
|
|
152
|
+
active = data.get("active")
|
|
153
|
+
approved = data.get("approved")
|
|
154
|
+
revision = data.get("revision")
|
|
155
|
+
restore = data.get("restoreMode", "full")
|
|
156
|
+
plan = data.get("plan", "")
|
|
157
|
+
goal = data.get("goal", "")
|
|
158
|
+
if not isinstance(active, bool) or not isinstance(approved, bool):
|
|
159
|
+
raise ValueError("规划模式条目缺少 active/approved 布尔字段")
|
|
160
|
+
if not isinstance(revision, int) or revision < 0:
|
|
161
|
+
raise ValueError(f"非法的规划模式版本号: {revision!r}")
|
|
162
|
+
if not isinstance(plan, str) or not isinstance(goal, str):
|
|
163
|
+
raise ValueError("规划模式条目的 plan/goal 必须是字符串")
|
|
164
|
+
if restore not in ("read-only", "plan", "accept-edits", "full"):
|
|
165
|
+
raise ValueError(f"非法的恢复权限模式: {restore!r}")
|
|
166
|
+
return PlanModeState(
|
|
167
|
+
active=active,
|
|
168
|
+
goal=goal,
|
|
169
|
+
plan=plan,
|
|
170
|
+
revision=revision,
|
|
171
|
+
approved=approved,
|
|
172
|
+
restore_mode=restore,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
type PlanModeNotifier = Callable[[PlanModeState, PlanModeReason], Awaitable[None]]
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def plan_command_intent(text: str) -> Literal["approve", "off"] | None:
|
|
180
|
+
"""审批提示里输入的斜杠命令 → 结论。
|
|
181
|
+
|
|
182
|
+
审批提示读的是自由文本,用户在等待审批时敲 ``/plan approve`` 或 ``/plan off``
|
|
183
|
+
是很自然的动作。把这两条命令认出来,比把它当成"修改意见"回给模型合理。
|
|
184
|
+
"""
|
|
185
|
+
body = text.strip()
|
|
186
|
+
if not body.startswith("/"):
|
|
187
|
+
return None
|
|
188
|
+
head, _, rest = body[1:].partition(" ")
|
|
189
|
+
if head.lower() != "plan":
|
|
190
|
+
return None
|
|
191
|
+
action = rest.strip().lower()
|
|
192
|
+
if action in ("approve", "ok"):
|
|
193
|
+
return "approve"
|
|
194
|
+
if action in ("off", "exit", "quit"):
|
|
195
|
+
return "off"
|
|
196
|
+
return None
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class PlanMode:
|
|
200
|
+
"""一个会话的规划模式:状态、持久化、权限模式切换与界面通知。
|
|
201
|
+
|
|
202
|
+
与 :class:`~braid_coding_agent.permissions.engine.PermissionEngine`、``PlanStore``
|
|
203
|
+
同构:每个会话一份,``/clear`` 与 RPC ``new_session`` 换会话时一起换掉。
|
|
204
|
+
|
|
205
|
+
构造即恢复:读当前分支上最后一条合法 ``plan_mode`` 条目,据此把权限引擎切到
|
|
206
|
+
``plan``(会话确实处于规划模式时)。没有权限引擎时无法保证只读,恢复出的
|
|
207
|
+
"规划模式"会被就地取消并留一条 warning——只读承诺不能靠提示词兑现。
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
def __init__(
|
|
211
|
+
self,
|
|
212
|
+
*,
|
|
213
|
+
session: SessionManager,
|
|
214
|
+
engine: PermissionEngine | None = None,
|
|
215
|
+
) -> None:
|
|
216
|
+
self._session = session
|
|
217
|
+
self._engine = engine
|
|
218
|
+
self._notify: PlanModeNotifier | None = None
|
|
219
|
+
self._tool: AgentTool | None = None
|
|
220
|
+
self._state = PlanModeState()
|
|
221
|
+
self._load()
|
|
222
|
+
self._restore_engine()
|
|
223
|
+
|
|
224
|
+
# ---------------------------------------------------------------- 只读
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def state(self) -> PlanModeState:
|
|
228
|
+
return self._state
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def tool(self) -> AgentTool | None:
|
|
232
|
+
"""``submit_plan`` 工具。装配层在构造完成后接进来;没接就没有提交入口。"""
|
|
233
|
+
return self._tool
|
|
234
|
+
|
|
235
|
+
@property
|
|
236
|
+
def active(self) -> bool:
|
|
237
|
+
return self._state.active
|
|
238
|
+
|
|
239
|
+
def attach_tool(self, tool: AgentTool) -> None:
|
|
240
|
+
self._tool = tool
|
|
241
|
+
|
|
242
|
+
def bind_notify(self, notify: PlanModeNotifier) -> None:
|
|
243
|
+
"""绑定会话的事件分发。装配顺序上会话晚于本对象出现,所以是后绑定。"""
|
|
244
|
+
self._notify = notify
|
|
245
|
+
|
|
246
|
+
# -------------------------------------------------------------- 状态变化
|
|
247
|
+
|
|
248
|
+
async def enter(self, goal: str = "") -> PlanModeState:
|
|
249
|
+
"""进入规划模式。已在规划模式时只更新目标。
|
|
250
|
+
|
|
251
|
+
:raises RuntimeError: 本次运行没有权限引擎。没有它,规划模式的只读承诺只剩
|
|
252
|
+
提示词,模型照样能改文件。
|
|
253
|
+
"""
|
|
254
|
+
engine = self._require_engine()
|
|
255
|
+
text = goal.strip()
|
|
256
|
+
if self._state.active:
|
|
257
|
+
if text and text != self._state.goal:
|
|
258
|
+
self._state = replace(self._state, goal=text)
|
|
259
|
+
self._persist()
|
|
260
|
+
await self._emit("entered")
|
|
261
|
+
return self._state
|
|
262
|
+
restore = engine.settings.mode
|
|
263
|
+
engine.set_mode("plan")
|
|
264
|
+
self._state = PlanModeState(
|
|
265
|
+
active=True,
|
|
266
|
+
goal=text,
|
|
267
|
+
restore_mode=restore,
|
|
268
|
+
updated_at=self._state.updated_at,
|
|
269
|
+
)
|
|
270
|
+
self._persist()
|
|
271
|
+
await self._emit("entered")
|
|
272
|
+
return self._state
|
|
273
|
+
|
|
274
|
+
async def submit(self, plan: str) -> PlanModeState:
|
|
275
|
+
"""记下一版完整计划,等待批准。
|
|
276
|
+
|
|
277
|
+
:raises RuntimeError: 当前不在规划模式。批准之后工具还留在可执行集合里,
|
|
278
|
+
这时再提交只会让人误以为又进入了规划。
|
|
279
|
+
:raises ValueError: 计划文本为空。
|
|
280
|
+
"""
|
|
281
|
+
text = plan.strip()
|
|
282
|
+
if not self._state.active:
|
|
283
|
+
raise RuntimeError("当前不在规划模式,不能提交计划")
|
|
284
|
+
if not text:
|
|
285
|
+
raise ValueError("计划内容不能为空")
|
|
286
|
+
self._state = replace(
|
|
287
|
+
self._state,
|
|
288
|
+
plan=text,
|
|
289
|
+
revision=self._state.revision + 1,
|
|
290
|
+
approved=False,
|
|
291
|
+
)
|
|
292
|
+
self._persist()
|
|
293
|
+
await self._emit("submitted")
|
|
294
|
+
return self._state
|
|
295
|
+
|
|
296
|
+
async def approve(self) -> PlanModeState:
|
|
297
|
+
"""用户批准:退出规划模式,恢复进入前的权限模式。
|
|
298
|
+
|
|
299
|
+
先落盘再切模式:落盘失败时权限仍停在 ``plan``(安全的方向),不会出现
|
|
300
|
+
"状态说已退出、引擎还只读"或反过来的半截状态。
|
|
301
|
+
|
|
302
|
+
:raises RuntimeError: 没有可批准的计划。
|
|
303
|
+
"""
|
|
304
|
+
if not self._state.has_plan:
|
|
305
|
+
raise RuntimeError("还没有可批准的计划")
|
|
306
|
+
engine = self._require_engine()
|
|
307
|
+
self._state = replace(self._state, active=False, approved=True)
|
|
308
|
+
self._persist()
|
|
309
|
+
engine.set_mode(self._state.restore_mode)
|
|
310
|
+
await self._emit("approved")
|
|
311
|
+
return self._state
|
|
312
|
+
|
|
313
|
+
async def revise(self) -> PlanModeState:
|
|
314
|
+
"""用户要求继续修改:保持规划模式,只通知界面。"""
|
|
315
|
+
await self._emit("revised")
|
|
316
|
+
return self._state
|
|
317
|
+
|
|
318
|
+
async def leave(self) -> PlanModeState:
|
|
319
|
+
"""退出规划模式。计划文档留在树上,``approved`` 归零。
|
|
320
|
+
|
|
321
|
+
与 :meth:`approve` 同序:先落盘,再切回进入前的权限模式。
|
|
322
|
+
"""
|
|
323
|
+
restore = self._state.restore_mode if self._state.active else None
|
|
324
|
+
self._state = replace(self._state, active=False, approved=False)
|
|
325
|
+
self._persist()
|
|
326
|
+
if restore is not None and self._engine is not None:
|
|
327
|
+
self._engine.set_mode(restore)
|
|
328
|
+
await self._emit("left")
|
|
329
|
+
return self._state
|
|
330
|
+
|
|
331
|
+
def reload(self) -> PlanModeState:
|
|
332
|
+
"""从当前分支重算状态(``/rewind`` 之后),并让权限引擎对齐。
|
|
333
|
+
|
|
334
|
+
回退可能把"进入规划模式"那条条目整个丢掉,也可能把"批准"丢掉。两种情况都要
|
|
335
|
+
让引擎跟着走:状态说退出、引擎还停在只读,模型会莫名其妙地被拒绝;状态说
|
|
336
|
+
规划中、引擎已经放开,只读承诺就只剩提示词了。
|
|
337
|
+
"""
|
|
338
|
+
was_active = self._state.active
|
|
339
|
+
restore_mode = self._state.restore_mode
|
|
340
|
+
self._load()
|
|
341
|
+
if self._state.active:
|
|
342
|
+
self._restore_engine()
|
|
343
|
+
elif was_active:
|
|
344
|
+
engine = self._engine
|
|
345
|
+
if engine is not None and engine.settings.mode == "plan":
|
|
346
|
+
engine.set_mode(restore_mode)
|
|
347
|
+
return self._state
|
|
348
|
+
|
|
349
|
+
def prompt_section(self) -> str:
|
|
350
|
+
"""当前要追加到系统提示词末尾的文本。空串表示不加。
|
|
351
|
+
|
|
352
|
+
规划中给指引与当前草稿;已批准给完整计划。两者都由状态算出,所以压缩之后
|
|
353
|
+
重新算一次就回到正确的样子,不依赖任何一条消息活下来。
|
|
354
|
+
"""
|
|
355
|
+
state = self._state
|
|
356
|
+
if state.active:
|
|
357
|
+
parts = [PLAN_MODE_INSTRUCTION.rstrip()]
|
|
358
|
+
if state.goal:
|
|
359
|
+
parts.append(f"本次规划的目标:{state.goal}")
|
|
360
|
+
if state.has_plan:
|
|
361
|
+
parts.append(f"当前计划草稿(第 {state.revision} 版,尚未批准):\n{state.plan}")
|
|
362
|
+
return "\n\n".join(parts)
|
|
363
|
+
if state.approved and state.has_plan:
|
|
364
|
+
return (
|
|
365
|
+
f"{APPROVED_PLAN_HEADER}\n\n"
|
|
366
|
+
f'<approved_plan revision="{state.revision}">\n{state.plan}\n</approved_plan>'
|
|
367
|
+
)
|
|
368
|
+
return ""
|
|
369
|
+
|
|
370
|
+
# ---------------------------------------------------------------- 内部
|
|
371
|
+
|
|
372
|
+
def _require_engine(self) -> PermissionEngine:
|
|
373
|
+
engine = self._engine
|
|
374
|
+
if engine is None:
|
|
375
|
+
raise RuntimeError(
|
|
376
|
+
"规划模式需要权限引擎:本次运行没有装配 PermissionEngine,无法保证只读。"
|
|
377
|
+
)
|
|
378
|
+
return engine
|
|
379
|
+
|
|
380
|
+
def _restore_engine(self) -> None:
|
|
381
|
+
"""构造时把权限引擎对齐到恢复出来的状态。"""
|
|
382
|
+
if not self._state.active:
|
|
383
|
+
return
|
|
384
|
+
engine = self._engine
|
|
385
|
+
if engine is None:
|
|
386
|
+
logger.warning("会话处于规划模式但没有权限引擎,已就地退出规划模式")
|
|
387
|
+
self._state = replace(self._state, active=False, approved=False)
|
|
388
|
+
self._persist()
|
|
389
|
+
return
|
|
390
|
+
engine.set_mode("plan")
|
|
391
|
+
|
|
392
|
+
async def _emit(self, reason: PlanModeReason) -> None:
|
|
393
|
+
notify = self._notify
|
|
394
|
+
if notify is not None:
|
|
395
|
+
await notify(self._state, reason)
|
|
396
|
+
|
|
397
|
+
def _persist(self) -> None:
|
|
398
|
+
payload: JsonValue = {
|
|
399
|
+
"active": self._state.active,
|
|
400
|
+
"goal": self._state.goal,
|
|
401
|
+
"plan": self._state.plan,
|
|
402
|
+
"revision": self._state.revision,
|
|
403
|
+
"approved": self._state.approved,
|
|
404
|
+
"restoreMode": self._state.restore_mode,
|
|
405
|
+
}
|
|
406
|
+
entry_id = self._session.append_custom(PLAN_MODE_CUSTOM_TYPE, payload)
|
|
407
|
+
entry = self._session.get_entry(entry_id)
|
|
408
|
+
if entry is not None:
|
|
409
|
+
self._state = replace(self._state, updated_at=entry.timestamp)
|
|
410
|
+
|
|
411
|
+
def _load(self) -> None:
|
|
412
|
+
"""从当前分支重算状态:最后一条合法条目胜出。"""
|
|
413
|
+
state = PlanModeState()
|
|
414
|
+
for entry in self._session.get_branch():
|
|
415
|
+
if not isinstance(entry, CustomEntry) or entry.custom_type != PLAN_MODE_CUSTOM_TYPE:
|
|
416
|
+
continue
|
|
417
|
+
try:
|
|
418
|
+
parsed = plan_mode_from_data(entry.data)
|
|
419
|
+
except ValueError as exc:
|
|
420
|
+
logger.warning("忽略无法解析的规划模式条目 %s:%s", entry.id, exc)
|
|
421
|
+
continue
|
|
422
|
+
state = replace(parsed, updated_at=entry.timestamp)
|
|
423
|
+
self._state = state
|