mainspring-coding-tools 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.
@@ -0,0 +1,154 @@
1
+ """mainspring-coding-tools:编码智能体工具外挂(M9,ADR-002 同款「能力走外挂」)。
2
+
3
+ core 提供「能不能跑 / 该不该跑」(Runner + Hook + Guardrail + HITL),本外挂提供
4
+ 「拿什么干活」:一组可直接进 ``Agent.tools`` 的编码工具 + 一个可配置的安全总闸。
5
+ core 零改动,外挂可整体卸载;与既有 extras 同规格(workspace 成员 / import-linter
6
+ 登记 / 显式装配),不新增第三方运行时依赖,工具实现全 stdlib。
7
+
8
+ 模块归属(T10-1 定骨架,后续卡逐格填实现):
9
+
10
+ files.py 读 / 写工具:read_file、write_file、edit_file(T10-2 / T10-3)
11
+ search.py 只读检索:glob、grep(T10-2)
12
+ web.py 出网工具:web_search、web_fetch(stdlib urllib + SSRF 防线,T15-⑥)
13
+ shell.py 命令执行:bash,沙箱引擎经装配层注入(T10-4)
14
+ jobs.py 后台任务:bash_bg / job_status / job_kill(T15-⑨)
15
+ coding.py todo 任务清单工具 + 编码 Agent 装配工厂(T10-5 / T10-7)
16
+ safety.py SafetyPolicy:项目根白名单 / 危险命令表 / 审批默认值(T10-6)
17
+ payload.py 结构化 payload 契约:版本号 / 基类 / 截断标志(T10-2 起)
18
+
19
+ 三条设计不变量(先定死,后补必返工):
20
+
21
+ 1. **工具结果一律结构化 payload**:路径、命中列表、unified diff、退出码、截断标志
22
+ 都是一等数据;文本只是投影。M11 前端的 diff / 卡片渲染直接消费它,禁止用裸
23
+ print 文本约定当接口。``@tool`` 会把 dict / BaseModel 序列化成 JSON 文本回填,
24
+ 所以 payload 的形状就是跨进程协议,改格式必须联动前端评审。
25
+ 2. **写 / 执行默认 require_approval**:不另起审批机制,直接经 core 的
26
+ ``Hook.pre_tool_use`` 三态裁决 + Runner 的 pending 快照;读类默认放行,
27
+ 开关可经 yaml 配置。任何安全组件异常一律降级 deny(fail-closed)。
28
+ 3. **沙箱 / 记忆等外挂不互 import**:import-linter 的 independence 契约禁止
29
+ extras 之间产生依赖箭头,需要复用 M7~M8 沙箱资产时走**装配层注入**
30
+ (同 core.config.backends 的间接装配口径),由 CLI / server 把引擎实例送进来。
31
+
32
+ 用法示例(T10-7 起:CLI 与 server 共用一处装配)::
33
+
34
+ from mainspring_coding_tools import (
35
+ SafetyPolicy, build_coding_agent, build_coding_tools, default_run_config,
36
+ )
37
+
38
+ policy = SafetyPolicy(Path.cwd())
39
+ agent = build_coding_agent(model, tools=build_coding_tools(policy), policy=policy)
40
+ result = await Runner().run(agent, "把 foo 重命名成 bar 并跑测试", cfg=default_run_config())
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ from pathlib import Path
46
+
47
+ from mainspring.tool import Tool
48
+
49
+ from .cli import CoderREPL, TerminalSink, render_event, render_pending
50
+ from .coding import (
51
+ CODING_AGENT_NAME,
52
+ DEFAULT_INSTRUCTIONS,
53
+ DEFAULT_MAX_TURNS,
54
+ DEFAULT_TOKEN_BUDGET,
55
+ TodoBindingHook,
56
+ TodoBoard,
57
+ TodoItem,
58
+ TodoStatus,
59
+ build_coding_agent,
60
+ build_coding_tools,
61
+ build_todo_tools,
62
+ default_run_config,
63
+ )
64
+ from .files import (
65
+ build_file_tools,
66
+ build_read_file_tools,
67
+ build_write_tools,
68
+ preview_diff_payload,
69
+ )
70
+ from .jobs import JobManager, build_background_tools
71
+ from .payload import PAYLOAD_VERSION
72
+ from .persona import CODING_PERSONA, PERSONA_NAME, PERSONA_VERSION
73
+ from .safety import (
74
+ COMMAND_TOOLS,
75
+ CONTROL_TOOLS,
76
+ ApprovalHook,
77
+ CommandSafetyHook,
78
+ SafetyHook,
79
+ SafetyPolicy,
80
+ SafetyTextGuardrail,
81
+ UnsafeCommand,
82
+ UnsafePath,
83
+ check_command,
84
+ )
85
+ from .search import build_search_tools
86
+ from .shell import CommandEngine, CommandPolicy, LocalEngine, build_shell_tools, run_command
87
+ from .web import (
88
+ DEFAULT_FETCH_MAX_CHARS,
89
+ DEFAULT_SEARCH_BACKEND,
90
+ build_web_tools,
91
+ web_fetch_payload,
92
+ web_search_payload,
93
+ )
94
+
95
+ __all__ = [
96
+ "CODING_AGENT_NAME",
97
+ "CODING_PERSONA",
98
+ "COMMAND_TOOLS",
99
+ "CONTROL_TOOLS",
100
+ "DEFAULT_FETCH_MAX_CHARS",
101
+ "DEFAULT_INSTRUCTIONS",
102
+ "DEFAULT_MAX_TURNS",
103
+ "DEFAULT_SEARCH_BACKEND",
104
+ "DEFAULT_TOKEN_BUDGET",
105
+ "PAYLOAD_VERSION",
106
+ "PERSONA_NAME",
107
+ "PERSONA_VERSION",
108
+ "ApprovalHook",
109
+ "CoderREPL",
110
+ "CommandEngine",
111
+ "CommandPolicy",
112
+ "CommandSafetyHook",
113
+ "JobManager",
114
+ "LocalEngine",
115
+ "SafetyHook",
116
+ "SafetyPolicy",
117
+ "SafetyTextGuardrail",
118
+ "TerminalSink",
119
+ "TodoBindingHook",
120
+ "TodoBoard",
121
+ "TodoItem",
122
+ "TodoStatus",
123
+ "UnsafeCommand",
124
+ "UnsafePath",
125
+ "build_background_tools",
126
+ "build_coding_agent",
127
+ "build_coding_tools",
128
+ "build_file_tools",
129
+ "build_read_file_tools",
130
+ "build_read_tools",
131
+ "build_search_tools",
132
+ "build_shell_tools",
133
+ "build_todo_tools",
134
+ "build_web_tools",
135
+ "build_write_tools",
136
+ "check_command",
137
+ "default_run_config",
138
+ "preview_diff_payload",
139
+ "render_event",
140
+ "render_pending",
141
+ "run_command",
142
+ "web_fetch_payload",
143
+ "web_search_payload",
144
+ ]
145
+
146
+
147
+ def build_read_tools(root: Path | str | SafetyPolicy | None = None) -> list[Tool]:
148
+ """只读工具组(T10-2):read_file / glob / grep,共用一份 SafetyPolicy。
149
+
150
+ 传 SafetyPolicy 时直接复用(写工具、执行工具将共用同一份策略对象);
151
+ 传路径或 None 时按该目录 / 当前工作目录构造。装配层只需造一次策略。
152
+ """
153
+ policy = root if isinstance(root, SafetyPolicy) else SafetyPolicy(Path(root or Path.cwd()))
154
+ return [*build_read_file_tools(policy), *build_search_tools(policy)]
@@ -0,0 +1,112 @@
1
+ """``python -m mainspring_coding_tools`` / ``mainspring-coder`` 的最小安装入口。
2
+
3
+ 本包已发 PyPI,安装后必须有可直接执行的入口;但外挂之间禁止互相 import
4
+ (import-linter 的 independence 契约),所以这里只用 core 的内存 store 与
5
+ 内置 ``LocalEngine``,不引入 session-sqlite / sandbox 两个外挂。
6
+
7
+ 需要「会话持久化 / 断电恢复 / 强隔离沙箱引擎」时,改用仓库内的完整装配件::
8
+
9
+ uv run --no-sync python examples/coding_cli.py --db .mainspring/coder.db --engine subprocess
10
+
11
+ 那条路径由应用层注入引擎与 sqlite 后端,能力更全;本入口定位是装完即用的
12
+ 零额外依赖 REPL(会话仅存活于本进程)。
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import asyncio
19
+ import contextlib
20
+ import os
21
+ import sys
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from mainspring.config import ModelConfig, ModelSettingsConfig, build_model
26
+ from mainspring.runner import Runner
27
+
28
+ from .cli import CoderREPL, TerminalSink
29
+ from .coding import build_coding_agent, build_coding_tools
30
+ from .safety import SafetyPolicy
31
+ from .shell import CommandPolicy, LocalEngine
32
+
33
+ __all__ = ["main"]
34
+
35
+
36
+ def _configure_console() -> None:
37
+ """Windows 控制台默认 cp936:显式切 UTF-8,避免中文提示 UnicodeEncodeError。"""
38
+ for stream in (sys.stdout, sys.stderr):
39
+ reconfigure = getattr(stream, "reconfigure", None)
40
+ if reconfigure is None:
41
+ continue
42
+ with contextlib.suppress(ValueError, OSError):
43
+ reconfigure(encoding="utf-8", errors="replace")
44
+
45
+
46
+ def _write(text: str) -> None:
47
+ sys.stdout.write(text)
48
+
49
+
50
+ async def _read_line(prompt: str) -> str:
51
+ _write(prompt)
52
+ sys.stdout.flush()
53
+ line = await asyncio.to_thread(sys.stdin.readline)
54
+ if line == "":
55
+ raise EOFError
56
+ return str(line).rstrip("\n")
57
+
58
+
59
+ def main(argv: list[str] | None = None) -> int:
60
+ parser = argparse.ArgumentParser(
61
+ prog="mainspring-coder",
62
+ description="mainspring 编码智能体(零额外依赖入口:内存会话 + LocalEngine)",
63
+ epilog="需要持久化会话或强隔离引擎请用 examples/coding_cli.py(--db / --engine)。",
64
+ )
65
+ parser.add_argument("--root", default=str(Path.cwd()), help="项目根(路径白名单边界)")
66
+ parser.add_argument("--model", default="qwen3:14b", help="模型名(/model 可切换)")
67
+ parser.add_argument(
68
+ "--provider", default=os.environ.get("MAINSPRING_PROVIDER", "ollama"), help="方言名"
69
+ )
70
+ parser.add_argument("--no-ansi", action="store_true", help="关闭颜色转义")
71
+ args = parser.parse_args(argv)
72
+ _configure_console()
73
+
74
+ policy = SafetyPolicy(Path(args.root).resolve())
75
+ engine = LocalEngine()
76
+ engine.check_available()
77
+ tools = build_coding_tools(
78
+ policy,
79
+ engine=engine,
80
+ # 引擎最小环境不继承宿主;透传 PATH 才能找到 python / pytest / git
81
+ command_policy=CommandPolicy(env_allowlist=("PATH",)),
82
+ )
83
+ runner = Runner(sink=TerminalSink(_write, ansi=not args.no_ansi))
84
+
85
+ def agent_for(name: str) -> Any:
86
+ chat = build_model(
87
+ ModelConfig(
88
+ provider=args.provider,
89
+ model=name,
90
+ settings=ModelSettingsConfig(temperature=0.0, max_output_tokens=4096),
91
+ )
92
+ )
93
+ return build_coding_agent(chat, tools, policy)
94
+
95
+ repl = CoderREPL(
96
+ runner=runner,
97
+ agent_for=agent_for,
98
+ model_name=args.model,
99
+ policy=policy,
100
+ write=_write,
101
+ read_line=_read_line,
102
+ ansi=not args.no_ansi,
103
+ )
104
+ try:
105
+ return asyncio.run(repl.run())
106
+ except KeyboardInterrupt:
107
+ sys.stdout.write("\n已中断\n")
108
+ return 130
109
+
110
+
111
+ if __name__ == "__main__":
112
+ sys.exit(main())
@@ -0,0 +1,362 @@
1
+ """编码智能体终端 REPL(T10-8):只做事件渲染与输入转发,零业务逻辑。
2
+
3
+ 边界是这张卡最重要的事,先写清再写代码:
4
+
5
+ examples/coding_cli.py(装配层) 拥有模型方言、SafetyPolicy、sqlite 后端工厂、
6
+ backends 注入、工具集、Agent 构造
7
+ cli.py(本模块) 只持有一个 Runner 与若干回调:读一行 →
8
+ 转发给 core 的 stream / approve / deny /
9
+ resume / shutdown → 把 RunEvent 渲染成 ANSI 文本
10
+
11
+ 因此本模块**不 import 任何方言、任何 session 后端、任何工具实现**,也不自己执行工具、
12
+ 不自己算审批结论、不自己读写会话库。它连「有哪些可恢复 run」都是问注入的
13
+ ``list_resumable`` 回调,而不是查库。这样 M10 的 server 换掉渲染层时,装配面一字不改:
14
+ 同一份 ``build_coding_agent`` + ``Runner`` 就是两端共用的全部逻辑。
15
+
16
+ 渲染只有两个出口:``render_event``(事件 → 文本)与 ``render_pending``(审批卡片 → 文本),
17
+ 都是纯函数,便于快照测试;``TerminalSink`` 是唯一写屏的地方,它同时覆盖流式 run 与
18
+ approve / deny 恢复后发出的事件(后者不进 stream 的 collector,只走 Runner.sink)。
19
+ 若把渲染塞进 ``async for`` 循环,恢复路径的事件就会凭空消失——这是最容易踩的坑。
20
+
21
+ 终端不引第三方 TUI 库(依赖红线),纯 ANSI 转义;控制台 UTF-8 由装配层显式
22
+ ``reconfigure``(Windows cp936 中文输出是已知坑位),本模块不碰 sys.stdout。
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ from collections.abc import Awaitable, Callable, Sequence
29
+ from typing import Any
30
+
31
+ from mainspring.agent import Agent
32
+ from mainspring.runner import Runner
33
+ from mainspring.types import RunEvent, ToolCall
34
+
35
+ from .coding import TodoBoard, default_run_config
36
+ from .files import preview_diff_payload
37
+ from .safety import SafetyPolicy
38
+
39
+ __all__ = ["CoderREPL", "TerminalSink", "render_event", "render_pending"]
40
+
41
+ _RESET = "\x1b[0m"
42
+ _DIM = "\x1b[2m"
43
+ _RED = "\x1b[31m"
44
+ _GREEN = "\x1b[32m"
45
+ _YELLOW = "\x1b[33m"
46
+ _CYAN = "\x1b[36m"
47
+
48
+ _COMMANDS = ("/new 新会话 /resume [run_id] 恢复中断的运行 /model <name> 切换模型 /quit 退出",)
49
+
50
+
51
+ def _paint(text: str, color: str, *, ansi: bool) -> str:
52
+ return f"{color}{text}{_RESET}" if ansi else text
53
+
54
+
55
+ def _tool_result_payload(event: RunEvent) -> dict[str, Any] | None:
56
+ """从 tool_call 事件的 content 还原结构化 payload;非 JSON 结果返回 None。"""
57
+ result = event.payload.get("result")
58
+ if not isinstance(result, dict):
59
+ return None
60
+ content = result.get("content")
61
+ if not isinstance(content, str):
62
+ return None
63
+ body = content.strip()
64
+ if body.startswith("<tool_result>") and body.endswith("</tool_result>"):
65
+ body = body[len("<tool_result>") : -len("</tool_result>")].strip()
66
+ try:
67
+ parsed = json.loads(body)
68
+ except ValueError:
69
+ return None
70
+ return parsed if isinstance(parsed, dict) else None
71
+
72
+
73
+ def render_event(event: RunEvent, *, ansi: bool = True) -> str | None:
74
+ """RunEvent → 一行(或一段)终端文本;纯函数,无 IO、无状态。
75
+
76
+ 流式文本逐片段原样吐出(不加换行),其余事件带前缀与换行;返回 None = 该类型静默。
77
+ """
78
+ payload = event.payload
79
+ kind = event.type
80
+ if kind == "llm_delta":
81
+ delta = payload.get("delta")
82
+ if not isinstance(delta, dict):
83
+ return None
84
+ if delta.get("type") == "text":
85
+ return str(delta.get("text", ""))
86
+ if delta.get("type") == "thinking":
87
+ return _paint(str(delta.get("thinking", "")), _DIM, ansi=ansi)
88
+ return None
89
+ if kind == "run_started":
90
+ return _paint(
91
+ f"\n[run {event.run_id}] {payload.get('agent_name', '')} 开始\n", _DIM, ansi=ansi
92
+ )
93
+ if kind == "tool_call":
94
+ name = payload.get("name", "?")
95
+ raw_result = payload.get("result")
96
+ result: dict[str, Any] = raw_result if isinstance(raw_result, dict) else {}
97
+ flag = "错误" if result.get("is_error") else "完成"
98
+ color = _RED if result.get("is_error") else _CYAN
99
+ lines = [_paint(f"\n[tool] {name} · {flag}", color, ansi=ansi)]
100
+ structured = _tool_result_payload(event)
101
+ if structured is not None:
102
+ diff = structured.get("unified_diff")
103
+ if isinstance(diff, str) and diff:
104
+ lines.append(diff)
105
+ elif "exit_code" in structured:
106
+ lines.append(
107
+ f"exit_code={structured['exit_code']} "
108
+ f"timed_out={structured.get('timed_out', False)}"
109
+ )
110
+ elif "items" in structured:
111
+ lines.append(str(structured.get("text", "")))
112
+ elif "matches" in structured:
113
+ lines.append(f"命中 {structured.get('count', 0)} 处")
114
+ return "\n".join(lines) + "\n"
115
+ if kind == "hook":
116
+ verdict = payload.get("verdict")
117
+ if verdict in {"deny", "require_approval"}:
118
+ return _paint(
119
+ f"\n[hook {payload.get('hook_name', '')}] {verdict}: {payload.get('reason', '')}\n",
120
+ _YELLOW,
121
+ ansi=ansi,
122
+ )
123
+ return None
124
+ if kind == "approval_pending":
125
+ return _paint(
126
+ f"\n[审批] 调用 {payload.get('call_id')} 挂起:{payload.get('reason', '')}\n",
127
+ _YELLOW,
128
+ ansi=ansi,
129
+ )
130
+ if kind == "approval_resolved":
131
+ decision = payload.get("decision")
132
+ color = _GREEN if decision == "approve" else _RED
133
+ return _paint(f"\n[审批] {decision} · {payload.get('call_id')}\n", color, ansi=ansi)
134
+ if kind == "run_finished":
135
+ usage = payload.get("total_usage") or {}
136
+ return _paint(
137
+ f"\n[完成] {payload.get('finish_reason', '')} "
138
+ f"tokens={usage.get('input_tokens', 0)}+{usage.get('output_tokens', 0)}\n",
139
+ _GREEN,
140
+ ansi=ansi,
141
+ )
142
+ if kind == "run_failed":
143
+ detail = f"{payload.get('exception_type', '')}: {payload.get('message_redacted', '')}"
144
+ return _paint(f"\n[失败] {detail}\n", _RED, ansi=ansi)
145
+ return None
146
+
147
+
148
+ def render_pending(call: ToolCall, preview: dict[str, Any], *, ansi: bool = True) -> str:
149
+ """审批卡片:调用名 + 参数 + 只读 diff 预览,人在 y/n 之前看到的就是批准后会发生的事。"""
150
+ lines = [_paint(f"┌─ 待审批 {call.name} ──────────────────────", _YELLOW, ansi=ansi)]
151
+ lines.append(f"│ call_id: {call.id}")
152
+ if preview.get("path"):
153
+ lines.append(f"│ 路径: {preview['path']}")
154
+ if preview.get("command"):
155
+ lines.append(f"│ 命令: {preview['command']}")
156
+ if preview.get("reason"):
157
+ lines.append(f"│ 提示: {preview['reason']}")
158
+ diff = preview.get("unified_diff")
159
+ if isinstance(diff, str) and diff:
160
+ for line in diff.splitlines():
161
+ lines.append(f"│ {line}")
162
+ else:
163
+ for line in str(preview.get("text", call.arguments)).splitlines():
164
+ lines.append(f"│ {line}")
165
+ lines.append(_paint("└──────────────────────────────────────────", _YELLOW, ansi=ansi))
166
+ return "\n".join(lines) + "\n"
167
+
168
+
169
+ class TerminalSink:
170
+ """唯一写屏出口:Runner.sink 上的每个事件都过 render_event。
171
+
172
+ approve / deny / resume 恢复出的事件同样走这里——它们不进 stream 的 collector。
173
+ """
174
+
175
+ def __init__(self, write: Callable[[str], None], *, ansi: bool = True) -> None:
176
+ self._write = write
177
+ self._ansi = ansi
178
+
179
+ async def emit(self, event: RunEvent) -> None:
180
+ text = render_event(event, ansi=self._ansi)
181
+ if text:
182
+ self._write(text)
183
+
184
+
185
+ class CoderREPL:
186
+ """输入循环:命令分发与 core API 转发,不含模型 / 工具 / 后端知识。"""
187
+
188
+ def __init__(
189
+ self,
190
+ *,
191
+ runner: Runner,
192
+ agent_for: Callable[[str], Agent],
193
+ model_name: str,
194
+ policy: SafetyPolicy,
195
+ write: Callable[[str], None],
196
+ read_line: Callable[[str], Awaitable[str]],
197
+ list_resumable: Callable[[], Awaitable[Sequence[str]]] | None = None,
198
+ ansi: bool = True,
199
+ session_id: str = "coding",
200
+ ) -> None:
201
+ self._runner = runner
202
+ self._agent_for = agent_for
203
+ self._model_name = model_name
204
+ self._policy = policy
205
+ self._write = write
206
+ self._read_line = read_line
207
+ self._list_resumable = list_resumable
208
+ self._ansi = ansi
209
+ self._session_id = session_id
210
+ self._session_seq = 1
211
+ self._board = TodoBoard()
212
+ self._last_run_id = ""
213
+ self._agent = agent_for(model_name)
214
+
215
+ @property
216
+ def session_id(self) -> str:
217
+ return self._session_id
218
+
219
+ @property
220
+ def last_run_id(self) -> str:
221
+ return self._last_run_id
222
+
223
+ def _prompt(self) -> str:
224
+ return _paint(f"[{self._model_name}] {self._session_id}> ", _CYAN, ansi=self._ansi)
225
+
226
+ async def run(self) -> int:
227
+ """主循环;返回退出码。Ctrl+C 经 core 的取消收口落库,重连用 /resume。"""
228
+ self._write(
229
+ _paint(
230
+ "mainspring-coder · 输入 /help 看命令,Ctrl+C 中断并落库\n", _DIM, ansi=self._ansi
231
+ )
232
+ )
233
+ while True:
234
+ try:
235
+ line = await self._read_line(self._prompt())
236
+ except (KeyboardInterrupt, EOFError):
237
+ return await self._interrupt()
238
+ text = line.strip()
239
+ if not text:
240
+ continue
241
+ if text.startswith("/"):
242
+ if await self._command(text):
243
+ return 0
244
+ continue
245
+ try:
246
+ await self._turn(text)
247
+ except (KeyboardInterrupt, EOFError):
248
+ return await self._interrupt()
249
+
250
+ async def _interrupt(self) -> int:
251
+ """Ctrl+C:显式补一次优雅停机落库,再由 core 的取消路径收口为 cancelled 快照。"""
252
+ count = await self._runner.shutdown()
253
+ self._write(
254
+ _paint(
255
+ f"\n已中断:落库 {count} 个在途快照;重启后用 /resume 恢复 {self._last_run_id}\n",
256
+ _YELLOW,
257
+ ansi=self._ansi,
258
+ )
259
+ )
260
+ return 130
261
+
262
+ async def _command(self, text: str) -> bool:
263
+ """返回 True 表示退出 REPL。命令只改本层状态或转发 core API。"""
264
+ head, _, arg = text.partition(" ")
265
+ arg = arg.strip()
266
+ if head == "/quit":
267
+ return True
268
+ if head == "/help":
269
+ self._write("\n".join(_COMMANDS) + "\n")
270
+ return False
271
+ if head == "/new":
272
+ self._session_seq += 1
273
+ self._session_id = f"coding-{self._session_seq}"
274
+ self._board = TodoBoard()
275
+ self._write(_paint(f"新会话 {self._session_id}\n", _DIM, ansi=self._ansi))
276
+ return False
277
+ if head == "/model":
278
+ if not arg:
279
+ self._write("用法: /model <模型名>\n")
280
+ return False
281
+ self._agent = self._agent_for(arg)
282
+ self._model_name = arg
283
+ self._write(_paint(f"模型切换为 {arg}\n", _DIM, ansi=self._ansi))
284
+ return False
285
+ if head == "/resume":
286
+ await self._resume(arg)
287
+ return False
288
+ self._write(f"未知命令 {head};输入 /help 看命令\n")
289
+ return False
290
+
291
+ async def _resume(self, arg: str) -> None:
292
+ run_id = arg
293
+ if not run_id:
294
+ candidates = await self._list_resumable() if self._list_resumable else []
295
+ run_id = candidates[-1] if candidates else self._last_run_id
296
+ if not run_id:
297
+ self._write("没有可恢复的 run;用法: /resume <run_id>\n")
298
+ return
299
+ self._write(_paint(f"恢复 {run_id}\n", _DIM, ansi=self._ansi))
300
+ await self._runner.resume(run_id, self._agent, deps=self._board)
301
+ self._last_run_id = run_id
302
+
303
+ async def _turn(self, text: str) -> None:
304
+ """一轮对话:消费 stream 事件取 run_id,再进入审批裁决循环。
305
+
306
+ 渲染一律由 TerminalSink 负责(包括恢复路径),这里绝不重复打印事件。
307
+ """
308
+ session = self._runner.session(self._session_id)
309
+ saw_approval = False
310
+ async for event in self._runner.stream(
311
+ self._agent,
312
+ text,
313
+ session=session,
314
+ deps=self._board,
315
+ cfg=default_run_config(),
316
+ ):
317
+ self._last_run_id = event.run_id
318
+ if event.type == "approval_pending":
319
+ saw_approval = True
320
+ # 正常结束的 run 没有挂起快照(checkpoint 里本就 Nothing to load),只有真见过
321
+ # approval_pending 才进裁决循环;否则每轮都会误报「挂起快照不可读」——
322
+ # 本机 Ollama 实跑里这条噪音刷了 6 次,是真机才暴露的形态。
323
+ if saw_approval:
324
+ await self._resolve_approvals(self._last_run_id)
325
+
326
+ async def _resolve_approvals(self, run_id: str) -> None:
327
+ """循环裁决,直到快照里再无待审批调用。
328
+
329
+ **真机冒烟揪出的根因(T10-8)**:``approve`` / ``deny`` 不是「一次裁决就收工」——
330
+ 最后一个 pending 被裁定后 core 会 ``_resume_snapshot`` 续跑,模型完全可能再调一次
331
+ 写 / 执行工具而**二次挂起**。若只处理 stream 结束时那一批 pending 就返回,run 会停在
332
+ pending、Session 保持 active;用户下一句话开新 run 时 ``session.begin_run()``
333
+ 直接抛 ``SessionBusy``(本机 Ollama 实跑复现:改完文件再跑 bash 验证时撞上)。
334
+ 因此每轮裁决后重新读快照,以 **checkpoint 的 pending 集合为权威**而不是以
335
+ stream 里见过的 call_id 为准;``seen`` 只防同一 call_id 被重复裁决。
336
+ """
337
+ seen: set[str] = set()
338
+ while True:
339
+ snapshot = await self._runner.checkpoint.load_run(run_id)
340
+ if snapshot is None:
341
+ self._write("挂起快照不可读,无法展示审批卡片\n")
342
+ return
343
+ fresh = [item for item in snapshot.pending if item.call.id not in seen]
344
+ if not fresh:
345
+ return
346
+ for pending in fresh:
347
+ seen.add(pending.call.id)
348
+ preview = preview_diff_payload(self._policy, pending.call)
349
+ self._write(render_pending(pending.call, preview, ansi=self._ansi))
350
+ answer = await self._read_line("批准? [y/N] ")
351
+ if answer.strip().lower() in {"y", "yes"}:
352
+ await self._runner.approve(
353
+ run_id, pending.call.id, self._agent, deps=self._board
354
+ )
355
+ else:
356
+ await self._runner.deny(
357
+ run_id,
358
+ pending.call.id,
359
+ self._agent,
360
+ deps=self._board,
361
+ reason="用户在终端拒绝,请改走别的方案",
362
+ )