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,953 @@
|
|
|
1
|
+
"""RPC 模式:用 stdin/stdout 的 JSONL 协议长驻控制一个会话。
|
|
2
|
+
|
|
3
|
+
实现分成"运行循环 + 命令分发 + 行读取器"三段,命令分发用一次 ``match``。
|
|
4
|
+
|
|
5
|
+
## 记录类型
|
|
6
|
+
|
|
7
|
+
- **命令**(stdin):``{"id"?: str, "type": str, ...}``;
|
|
8
|
+
- **响应**(stdout):``{"id"?: str, "type": "response", "command": str, "success": bool}``,
|
|
9
|
+
成功时带 ``data``,失败时带 ``error``;
|
|
10
|
+
- **事件**(stdout):与 ``--mode json`` 完全同形(:func:`session_event_to_wire`),
|
|
11
|
+
不带命令 ``id``;
|
|
12
|
+
- **权限**(stdout/stdin):``permission_request`` 与 ``permission_response``。权限引擎
|
|
13
|
+
判定为 ``ask`` 时写出前一条并挂起这次工具调用,客户端用同名命令把批准范围送回来;
|
|
14
|
+
服务端收到后写出后一条作为审计确认。
|
|
15
|
+
- **提问**(stdout/stdin):``question_request`` 与 ``question_response``。``question``
|
|
16
|
+
工具需要用户回答时写出前一条并挂起,客户端带 ``selected``/``custom`` 回答;
|
|
17
|
+
双缺省按取消处理,服务端收到后同样写出审计确认。
|
|
18
|
+
|
|
19
|
+
``id`` 是客户端自选的关联键,响应原样带回。事件与响应都是"会话活动"或"命令结果",
|
|
20
|
+
两者会交错,所以写入必须串行(见 :attr:`RpcServer._write_lock`)。
|
|
21
|
+
权限与提问的 ``requestId`` 关联的是一次工具调用,不是一条客户端命令;
|
|
22
|
+
两类请求的编号空间分开(``permission-N`` / ``question-N``),按 ``requestId`` 配对。
|
|
23
|
+
|
|
24
|
+
## 为什么 RPC 不发会话头
|
|
25
|
+
|
|
26
|
+
``--mode json`` 的第一行是 ``{"type":"session", ...}``:那是一次性的单发进程,
|
|
27
|
+
消费方需要知道"这批事件属于哪个会话"。RPC 进程是长驻的,会话可以在中途被
|
|
28
|
+
``new_session`` 换掉,一行头既描述不了全程,也会让"头只出现一次"这条单发契约
|
|
29
|
+
变成谎言。会话标识改由 ``get_state.sessionId`` 按需查询。
|
|
30
|
+
|
|
31
|
+
## 契约要点
|
|
32
|
+
|
|
33
|
+
- **响应只覆盖命令处理,不覆盖模型工作。** ``prompt`` 的响应在 run *被接受*时
|
|
34
|
+
就发出(``disposition: "started"``),模型的成败随后由事件流表达。把响应攒到
|
|
35
|
+
run 结束才发,客户端就没法在同一个连接上继续发 ``abort``。
|
|
36
|
+
- **长命令不阻塞事件。** ``prompt`` 起后台任务,读循环立刻回去读下一行;其余命令
|
|
37
|
+
按到达顺序串行处理。
|
|
38
|
+
- **任何异常都变成错误响应**,异常信息只进日志(stderr 侧),stdout 上永远只有协议记录。
|
|
39
|
+
- **关掉 stdin 就是优雅退出**:退订事件、``dispose`` 会话(取消在跑的 run)、
|
|
40
|
+
等后台任务收尾,然后返回。挂起的权限与提问全部按拒绝/取消收尾。
|
|
41
|
+
- **``SIGTERM`` / ``SIGHUP`` 也走同一条收尾**:停止读循环,取消在跑的
|
|
42
|
+
run,等它把 ``aborted`` 消息写进会话,刷 stdout,返回 143 / 129。服务化部署时
|
|
43
|
+
进程管理器发的就是 ``SIGTERM``,客户端因此仍能收到 ``agent_settled``。
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
from __future__ import annotations
|
|
47
|
+
|
|
48
|
+
import asyncio
|
|
49
|
+
import codecs
|
|
50
|
+
import json
|
|
51
|
+
import logging
|
|
52
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
|
|
53
|
+
from dataclasses import dataclass
|
|
54
|
+
from typing import Any, Final, cast
|
|
55
|
+
|
|
56
|
+
from braid_ai.cancel import CancelToken
|
|
57
|
+
from braid_ai.types import ImageContent, JsonValue, ModelThinkingLevel
|
|
58
|
+
from braid_coding_agent.checkpoint import CheckpointError, CheckpointStore
|
|
59
|
+
from braid_coding_agent.checkpoint.git import GitError
|
|
60
|
+
from braid_coding_agent.compaction.summarize import SummarizationError
|
|
61
|
+
from braid_coding_agent.mcp import McpRuntime, McpServerStatus
|
|
62
|
+
from braid_coding_agent.modes.json_mode import (
|
|
63
|
+
compaction_result_to_wire,
|
|
64
|
+
model_to_wire,
|
|
65
|
+
session_event_to_wire,
|
|
66
|
+
transcript_message_to_wire,
|
|
67
|
+
)
|
|
68
|
+
from braid_coding_agent.modes.wire import (
|
|
69
|
+
checkpoint_wire,
|
|
70
|
+
diff_wire,
|
|
71
|
+
mcp_status_wire,
|
|
72
|
+
undo_wire,
|
|
73
|
+
)
|
|
74
|
+
from braid_coding_agent.permissions.engine import (
|
|
75
|
+
APPROVAL_SCOPES,
|
|
76
|
+
ApprovalAnswer,
|
|
77
|
+
PermissionPrompt,
|
|
78
|
+
)
|
|
79
|
+
from braid_coding_agent.questions import QuestionAnswer, QuestionRequest
|
|
80
|
+
from braid_coding_agent.session.agent_session import AgentSession, SessionEvent
|
|
81
|
+
from braid_coding_agent.session.status import plan_mode_wire, plan_wire, status_wire_parts
|
|
82
|
+
from braid_coding_agent.startup.monitor import StartupMonitor
|
|
83
|
+
from braid_coding_agent.startup.scheduler import BackgroundScheduler, ScheduledTask
|
|
84
|
+
from braid_coding_agent.subagents.runtime import SubagentRuntime
|
|
85
|
+
|
|
86
|
+
from .lifecycle import TerminationHandler, shutdown_session
|
|
87
|
+
|
|
88
|
+
logger = logging.getLogger(__name__)
|
|
89
|
+
|
|
90
|
+
#: 一行协议记录。JSON 边界,值类型只能是 JSON 能表达的。
|
|
91
|
+
type JsonRecord = dict[str, Any]
|
|
92
|
+
|
|
93
|
+
#: 写一条协议的出口。实现方负责真正落到 stdout 并 flush。
|
|
94
|
+
type Stdout = Callable[[JsonRecord], Awaitable[None]]
|
|
95
|
+
|
|
96
|
+
#: 造一个新会话。参数是"被替换掉的那个会话"与"头的 ``parentSession``"。
|
|
97
|
+
#:
|
|
98
|
+
#: 传入被替换的会话是为了让它自己回答"cwd 在哪、要不要落盘"——装配参数在组合根,
|
|
99
|
+
#: RPC 层不该知道 ``--session-dir`` 这类细节(与 REPL 的 ``build_session`` 同一思路)。
|
|
100
|
+
type NewSessionFn = Callable[[AgentSession, "str | None"], Awaitable[AgentSession]]
|
|
101
|
+
|
|
102
|
+
#: 思考级别的七个档位。
|
|
103
|
+
_THINKING_LEVELS: Final[frozenset[str]] = frozenset(
|
|
104
|
+
{"off", "minimal", "low", "medium", "high", "xhigh", "max"}
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
#: 三句拒绝文案。RPC 的错误文本是协议的一部分,客户端会按它分支,
|
|
108
|
+
#: 所以这里不翻译(其余 CLI 文案仍是中文)。
|
|
109
|
+
_DISPOSED = "Session has been disposed"
|
|
110
|
+
_COMPACTING = (
|
|
111
|
+
"Cannot submit a prompt while compaction is in progress. "
|
|
112
|
+
"Wait for compaction to finish and retry."
|
|
113
|
+
)
|
|
114
|
+
_BUSY = (
|
|
115
|
+
"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') "
|
|
116
|
+
"to queue the message."
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class _InvalidCommand(ValueError):
|
|
121
|
+
"""命令字段不合法。转成 ``success: false`` 的响应,不打断读循环。"""
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(slots=True)
|
|
125
|
+
class _PendingPermission:
|
|
126
|
+
"""一条等待客户端回答的权限请求。``tool`` 只用于响应的审计记录。"""
|
|
127
|
+
|
|
128
|
+
future: asyncio.Future[ApprovalAnswer]
|
|
129
|
+
tool: str
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(slots=True)
|
|
133
|
+
class _PendingQuestion:
|
|
134
|
+
"""一条等待客户端回答的提问。``question`` 只用于审计记录。"""
|
|
135
|
+
|
|
136
|
+
future: asyncio.Future[QuestionAnswer]
|
|
137
|
+
question: str
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ------------------------------------------------------------------ 行切分
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
async def iter_json_lines(chunks: AsyncIterator[bytes]) -> AsyncIterator[str]:
|
|
144
|
+
"""把字节流切成 JSONL 记录(不含行尾)。
|
|
145
|
+
|
|
146
|
+
三条规则都是踩过的坑:
|
|
147
|
+
|
|
148
|
+
- **只按 ``\\n`` 切**。``readline`` 一类的读取器还会在 ``U+2028``/``U+2029``
|
|
149
|
+
处断行,而这两个字符在 JSON 字符串里是合法的(模型输出里就有);
|
|
150
|
+
- **容忍 CRLF**:行尾的 ``\\r`` 去掉,不当成 JSON 的一部分;
|
|
151
|
+
- **增量解码 UTF-8**:一个中文字符可能被拆在两个 chunk 里,逐 chunk
|
|
152
|
+
``decode`` 会直接抛错。
|
|
153
|
+
|
|
154
|
+
最后一段没有换行的内容照样产出一行。
|
|
155
|
+
"""
|
|
156
|
+
decoder = codecs.getincrementaldecoder("utf-8")()
|
|
157
|
+
buffer = ""
|
|
158
|
+
async for chunk in chunks:
|
|
159
|
+
buffer += decoder.decode(chunk)
|
|
160
|
+
while (index := buffer.find("\n")) != -1:
|
|
161
|
+
line = buffer[:index]
|
|
162
|
+
buffer = buffer[index + 1 :]
|
|
163
|
+
yield line[:-1] if line.endswith("\r") else line
|
|
164
|
+
buffer += decoder.decode(b"", final=True)
|
|
165
|
+
if buffer:
|
|
166
|
+
yield buffer
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ------------------------------------------------------------------ 记录构造
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _success(request_id: str | None, command: str, data: JsonRecord | None = None) -> JsonRecord:
|
|
173
|
+
"""成功响应。``data`` 省略表示"这个命令没有返回值"。"""
|
|
174
|
+
record: JsonRecord = {
|
|
175
|
+
"type": "response",
|
|
176
|
+
"command": command,
|
|
177
|
+
"success": True,
|
|
178
|
+
}
|
|
179
|
+
if request_id is not None:
|
|
180
|
+
record["id"] = request_id
|
|
181
|
+
if data is not None:
|
|
182
|
+
record["data"] = data
|
|
183
|
+
return record
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _error(request_id: str | None, command: str, message: str) -> JsonRecord:
|
|
187
|
+
"""失败响应。``id`` 缺失就不写这个键(解析失败时本来也没有 id)。"""
|
|
188
|
+
record: JsonRecord = {
|
|
189
|
+
"type": "response",
|
|
190
|
+
"command": command,
|
|
191
|
+
"success": False,
|
|
192
|
+
"error": message,
|
|
193
|
+
}
|
|
194
|
+
if request_id is not None:
|
|
195
|
+
record["id"] = request_id
|
|
196
|
+
return record
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _task_wire(task: ScheduledTask) -> JsonRecord:
|
|
200
|
+
"""后台任务快照 → 协议记录。``priority`` 用数值,客户端自己排顺序。"""
|
|
201
|
+
return {
|
|
202
|
+
"name": task.name,
|
|
203
|
+
"priority": int(task.priority),
|
|
204
|
+
"policy": task.policy,
|
|
205
|
+
"state": task.state,
|
|
206
|
+
"attempts": task.attempts,
|
|
207
|
+
"durationMs": round(task.duration_ms, 3),
|
|
208
|
+
"cpuMs": round(task.cpu_ms, 3),
|
|
209
|
+
"error": task.error,
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _require_str(command: Mapping[str, JsonValue], key: str, kind: str) -> str:
|
|
214
|
+
"""必填字符串字段。缺了或类型不对都算客户端的问题,直接回一条错误响应。"""
|
|
215
|
+
value = command.get(key)
|
|
216
|
+
if not isinstance(value, str):
|
|
217
|
+
raise _InvalidCommand(f"{kind} requires a string '{key}' field")
|
|
218
|
+
return value
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _opt_str(command: Mapping[str, JsonValue], key: str, kind: str) -> str | None:
|
|
222
|
+
"""可选字符串字段。存在但类型不对同样报错——静默忽略等于丢掉用户输入。"""
|
|
223
|
+
value = command.get(key)
|
|
224
|
+
if value is None:
|
|
225
|
+
return None
|
|
226
|
+
if not isinstance(value, str):
|
|
227
|
+
raise _InvalidCommand(f"{kind} requires '{key}' to be a string")
|
|
228
|
+
return value
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _images_from(command: Mapping[str, JsonValue]) -> list[ImageContent] | None:
|
|
232
|
+
"""``images`` 字段 → 内容块。形状与消息 wire 里的图片块一致。"""
|
|
233
|
+
raw = command.get("images")
|
|
234
|
+
if raw is None:
|
|
235
|
+
return None
|
|
236
|
+
if not isinstance(raw, list):
|
|
237
|
+
raise _InvalidCommand("'images' must be an array of image content blocks")
|
|
238
|
+
images: list[ImageContent] = []
|
|
239
|
+
for item in raw:
|
|
240
|
+
if not isinstance(item, dict):
|
|
241
|
+
raise _InvalidCommand("each image must be an object")
|
|
242
|
+
data = item.get("data")
|
|
243
|
+
mime_type = item.get("mimeType")
|
|
244
|
+
if not isinstance(data, str) or not isinstance(mime_type, str):
|
|
245
|
+
raise _InvalidCommand("image requires string 'data' and 'mimeType' fields")
|
|
246
|
+
images.append(ImageContent(data=data, mime_type=mime_type))
|
|
247
|
+
return images or None
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
# ------------------------------------------------------------------ 服务器
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class RpcServer:
|
|
254
|
+
"""一条 stdin/stdout 上的长驻会话。
|
|
255
|
+
|
|
256
|
+
:param session: 初始会话。``new_session`` 之后指向新的那个。
|
|
257
|
+
:param new_session: 造新会话的回调。``None`` 表示这个运行时没有会话管理能力,
|
|
258
|
+
``new_session`` 命令会回一条错误响应,不假装成功。
|
|
259
|
+
:param mcp: MCP 运行时。``mcp_status`` 从这里读状态;``None`` 时回空列表。
|
|
260
|
+
:param subagents: 子代理运行时。``get_agents`` 从这里读定义与任务状态。
|
|
261
|
+
:param monitor: 启动监控。``get_monitor`` 从这里读检查点与派生指标。
|
|
262
|
+
:param scheduler: 后台调度器。``get_monitor`` 同时返回任务快照。
|
|
263
|
+
|
|
264
|
+
生命周期只有一次::meth:`run` 退订、释放会话、等后台任务收尾,然后返回。
|
|
265
|
+
"""
|
|
266
|
+
|
|
267
|
+
def __init__(
|
|
268
|
+
self,
|
|
269
|
+
*,
|
|
270
|
+
session: AgentSession,
|
|
271
|
+
new_session: NewSessionFn | None = None,
|
|
272
|
+
mcp: McpRuntime | None = None,
|
|
273
|
+
subagents: SubagentRuntime | None = None,
|
|
274
|
+
monitor: StartupMonitor | None = None,
|
|
275
|
+
scheduler: BackgroundScheduler | None = None,
|
|
276
|
+
) -> None:
|
|
277
|
+
self._session = session
|
|
278
|
+
self._new_session_factory = new_session
|
|
279
|
+
self._mcp = mcp
|
|
280
|
+
self._subagents = subagents
|
|
281
|
+
self._monitor = monitor
|
|
282
|
+
self._scheduler = scheduler
|
|
283
|
+
self._stdout: Stdout | None = None
|
|
284
|
+
self._write_lock: asyncio.Lock | None = None
|
|
285
|
+
self._unsubscribe: Callable[[], None] | None = None
|
|
286
|
+
self._run_tasks: set[asyncio.Task[None]] = set()
|
|
287
|
+
#: 有一条 prompt 已被接受、但 run 还没真正开始(见 :meth:`_is_busy`)。
|
|
288
|
+
self._run_pending = False
|
|
289
|
+
#: 权限请求按 requestId 配对;客户端离线时全部按拒绝收尾。
|
|
290
|
+
self._pending_permissions: dict[str, _PendingPermission] = {}
|
|
291
|
+
self._permission_counter = 0
|
|
292
|
+
#: 提问请求同样按 requestId 配对;收尾语义与权限一致(按取消)。
|
|
293
|
+
self._pending_questions: dict[str, _PendingQuestion] = {}
|
|
294
|
+
self._question_counter = 0
|
|
295
|
+
self._client_online = False
|
|
296
|
+
|
|
297
|
+
# ------------------------------------------------------------ 只读状态
|
|
298
|
+
|
|
299
|
+
@property
|
|
300
|
+
def session(self) -> AgentSession:
|
|
301
|
+
"""当前会话。``new_session`` 之后指向新的那个。"""
|
|
302
|
+
return self._session
|
|
303
|
+
|
|
304
|
+
# ---------------------------------------------------------------- 主循环
|
|
305
|
+
|
|
306
|
+
async def run(
|
|
307
|
+
self,
|
|
308
|
+
stdin: AsyncIterator[bytes],
|
|
309
|
+
stdout: Stdout,
|
|
310
|
+
*,
|
|
311
|
+
flush: Callable[[], None] | None = None,
|
|
312
|
+
) -> int:
|
|
313
|
+
"""读到 stdin 结束或收到终止信号为止,返回进程退出码。
|
|
314
|
+
|
|
315
|
+
读循环是单消费者:命令按到达顺序处理。``prompt`` 会起一个后台任务跑整次
|
|
316
|
+
run,因此"发一条 prompt 再发 abort"在同一个连接上成立——这正是响应必须
|
|
317
|
+
早于 run 结束发出的原因。
|
|
318
|
+
|
|
319
|
+
退出码只区分"正常结束"(0)与"被信号打断"(143 / 129):协议内部的失败
|
|
320
|
+
都是响应,不是进程失败。
|
|
321
|
+
|
|
322
|
+
:param flush: 收尾时刷新 stdout。协议通道丢了半行,客户端会一直等下去。
|
|
323
|
+
"""
|
|
324
|
+
if self._stdout is not None:
|
|
325
|
+
raise RuntimeError("RpcServer.run() 只能调用一次")
|
|
326
|
+
self._stdout = stdout
|
|
327
|
+
self._write_lock = asyncio.Lock()
|
|
328
|
+
self._client_online = True
|
|
329
|
+
self._unsubscribe = self._session.subscribe(self._on_event)
|
|
330
|
+
handler = TerminationHandler()
|
|
331
|
+
handler.install()
|
|
332
|
+
reader = asyncio.create_task(self._read_loop(stdin))
|
|
333
|
+
exit_code = 0
|
|
334
|
+
try:
|
|
335
|
+
if handler.installed:
|
|
336
|
+
watcher = asyncio.create_task(handler.wait())
|
|
337
|
+
try:
|
|
338
|
+
await asyncio.wait({reader, watcher}, return_when=asyncio.FIRST_COMPLETED)
|
|
339
|
+
finally:
|
|
340
|
+
watcher.cancel()
|
|
341
|
+
await asyncio.gather(watcher, return_exceptions=True)
|
|
342
|
+
if reader.done():
|
|
343
|
+
# 读循环里未预期的异常照常抛出:那是代码缺陷,不是协议数据。
|
|
344
|
+
reader.result()
|
|
345
|
+
else:
|
|
346
|
+
exit_code = handler.exit_code
|
|
347
|
+
else:
|
|
348
|
+
await reader
|
|
349
|
+
finally:
|
|
350
|
+
handler.close()
|
|
351
|
+
# 先停读循环再释放会话:新的命令不该在收尾途中被接受。
|
|
352
|
+
reader.cancel()
|
|
353
|
+
await asyncio.gather(reader, return_exceptions=True)
|
|
354
|
+
# 客户端走了就没有批准与回答来源:挂起的调用按拒绝/取消收尾,run 才能结束,
|
|
355
|
+
# shutdown_session 才不会一直等一个永远不醒的后台任务。
|
|
356
|
+
self._client_online = False
|
|
357
|
+
self._deny_pending_permissions("客户端已离线")
|
|
358
|
+
self._deny_pending_questions("客户端已离线")
|
|
359
|
+
await shutdown_session(
|
|
360
|
+
self._session,
|
|
361
|
+
unsubscribe=self._detach_events,
|
|
362
|
+
drain=self._drain_run_tasks,
|
|
363
|
+
flush=flush,
|
|
364
|
+
)
|
|
365
|
+
self._stdout = None
|
|
366
|
+
self._write_lock = None
|
|
367
|
+
return exit_code
|
|
368
|
+
|
|
369
|
+
def _detach_events(self) -> None:
|
|
370
|
+
"""退订会话事件。收尾路径与 ``new_session`` 共用。"""
|
|
371
|
+
if self._unsubscribe is not None:
|
|
372
|
+
self._unsubscribe()
|
|
373
|
+
self._unsubscribe = None
|
|
374
|
+
|
|
375
|
+
async def _read_loop(self, stdin: AsyncIterator[bytes]) -> None:
|
|
376
|
+
"""一行一条命令,直到 stdin 结束。
|
|
377
|
+
|
|
378
|
+
客户端把读端关了(``BrokenPipeError``)就没有接收方,继续读下去也只会在
|
|
379
|
+
下一次写时炸;非法 UTF-8 是一条协议数据,回错误响应后继续。
|
|
380
|
+
"""
|
|
381
|
+
try:
|
|
382
|
+
async for line in iter_json_lines(stdin):
|
|
383
|
+
await self._handle_line(line)
|
|
384
|
+
except BrokenPipeError:
|
|
385
|
+
logger.debug("RPC 客户端关闭了 stdout,停止读循环")
|
|
386
|
+
except UnicodeDecodeError as exc:
|
|
387
|
+
await self._emit(_error(None, "parse", f"Failed to parse command: {exc}"))
|
|
388
|
+
finally:
|
|
389
|
+
# stdin 关闭就等于批准与回答通道消失,不必等引擎的超时上限。
|
|
390
|
+
self._client_online = False
|
|
391
|
+
self._deny_pending_permissions("客户端已离线")
|
|
392
|
+
self._deny_pending_questions("客户端已离线")
|
|
393
|
+
|
|
394
|
+
async def _handle_line(self, line: str) -> None:
|
|
395
|
+
"""一行 → 解析 → 处理 → 写响应。解析失败不打断循环。"""
|
|
396
|
+
try:
|
|
397
|
+
parsed: object = json.loads(line)
|
|
398
|
+
except json.JSONDecodeError as exc:
|
|
399
|
+
await self._emit(_error(None, "parse", f"Failed to parse command: {exc.msg}"))
|
|
400
|
+
return
|
|
401
|
+
if not isinstance(parsed, dict):
|
|
402
|
+
await self._emit(
|
|
403
|
+
_error(None, "parse", "Failed to parse command: expected a JSON object")
|
|
404
|
+
)
|
|
405
|
+
return
|
|
406
|
+
response = await self.handle(cast(dict[str, JsonValue], parsed))
|
|
407
|
+
await self._emit(response)
|
|
408
|
+
|
|
409
|
+
# ---------------------------------------------------------------- 命令
|
|
410
|
+
|
|
411
|
+
async def handle(self, command: Mapping[str, JsonValue]) -> JsonRecord:
|
|
412
|
+
"""处理一条命令,返回要写出的响应记录。**永不抛异常。**
|
|
413
|
+
|
|
414
|
+
命令处理的任何失败都是协议数据(``success: false``):RPC 是进程边界,
|
|
415
|
+
调用方看不到我们的异常信息,把异常漏出去只会让客户端读到半个进程的输出。
|
|
416
|
+
真正的诊断走日志。
|
|
417
|
+
"""
|
|
418
|
+
raw_id = command.get("id")
|
|
419
|
+
request_id = raw_id if isinstance(raw_id, str) else None
|
|
420
|
+
kind = command.get("type")
|
|
421
|
+
if not isinstance(kind, str):
|
|
422
|
+
return _error(request_id, "parse", "Command is missing a string 'type' field")
|
|
423
|
+
try:
|
|
424
|
+
return await self._dispatch(kind, request_id, command)
|
|
425
|
+
except _InvalidCommand as exc:
|
|
426
|
+
return _error(request_id, kind, str(exc))
|
|
427
|
+
except Exception as exc:
|
|
428
|
+
logger.exception("RPC 命令 %s 处理失败", kind)
|
|
429
|
+
return _error(request_id, kind, str(exc) or type(exc).__name__)
|
|
430
|
+
|
|
431
|
+
async def _dispatch(
|
|
432
|
+
self, kind: str, request_id: str | None, command: Mapping[str, JsonValue]
|
|
433
|
+
) -> JsonRecord:
|
|
434
|
+
match kind:
|
|
435
|
+
case "prompt":
|
|
436
|
+
return await self._prompt(request_id, command)
|
|
437
|
+
case "steer":
|
|
438
|
+
return await self._queue(request_id, command, kind)
|
|
439
|
+
case "follow_up":
|
|
440
|
+
return await self._queue(request_id, command, kind)
|
|
441
|
+
case "abort":
|
|
442
|
+
self._deny_pending_permissions("运行被取消")
|
|
443
|
+
self._deny_pending_questions("运行被取消")
|
|
444
|
+
await self._session.abort()
|
|
445
|
+
return _success(request_id, kind)
|
|
446
|
+
case "permission_response":
|
|
447
|
+
return await self._permission_response(request_id, command)
|
|
448
|
+
case "question_response":
|
|
449
|
+
return await self._question_response(request_id, command)
|
|
450
|
+
case "get_state":
|
|
451
|
+
return _success(request_id, kind, self._state())
|
|
452
|
+
case "plan":
|
|
453
|
+
return await self._plan(request_id, command)
|
|
454
|
+
case "get_messages":
|
|
455
|
+
return _success(
|
|
456
|
+
request_id,
|
|
457
|
+
kind,
|
|
458
|
+
{
|
|
459
|
+
"messages": [
|
|
460
|
+
transcript_message_to_wire(message)
|
|
461
|
+
for message in self._session.agent.state.messages
|
|
462
|
+
]
|
|
463
|
+
},
|
|
464
|
+
)
|
|
465
|
+
case "set_model":
|
|
466
|
+
return await self._set_model(request_id, command)
|
|
467
|
+
case "set_thinking_level":
|
|
468
|
+
return await self._set_thinking_level(request_id, command)
|
|
469
|
+
case "compact":
|
|
470
|
+
return await self._compact(request_id, command)
|
|
471
|
+
case "undo":
|
|
472
|
+
return await self._undo(request_id, kind)
|
|
473
|
+
case "redo":
|
|
474
|
+
return await self._redo(request_id, kind)
|
|
475
|
+
case "get_diff":
|
|
476
|
+
return await self._get_diff(request_id, kind)
|
|
477
|
+
case "new_session":
|
|
478
|
+
return await self._new_session(request_id, command)
|
|
479
|
+
case "mcp_status":
|
|
480
|
+
return _success(
|
|
481
|
+
request_id,
|
|
482
|
+
kind,
|
|
483
|
+
{"servers": [mcp_status_wire(status) for status in self._mcp_statuses()]},
|
|
484
|
+
)
|
|
485
|
+
case "get_agents":
|
|
486
|
+
return _success(request_id, kind, self._agents_state())
|
|
487
|
+
case "get_monitor":
|
|
488
|
+
return _success(request_id, kind, self._monitor_state())
|
|
489
|
+
case _:
|
|
490
|
+
return _error(request_id, kind, f"Unknown command: {kind}")
|
|
491
|
+
|
|
492
|
+
async def _prompt(self, request_id: str | None, command: Mapping[str, JsonValue]) -> JsonRecord:
|
|
493
|
+
"""提交一次 prompt。
|
|
494
|
+
|
|
495
|
+
三种去向:正在跑就按
|
|
496
|
+
``streamingBehavior`` 排队、正在压缩就拒绝、空闲就起一次 run。响应里的
|
|
497
|
+
``disposition`` 说明这次提交去了哪条路。
|
|
498
|
+
"""
|
|
499
|
+
kind = "prompt"
|
|
500
|
+
text = _require_str(command, "message", kind)
|
|
501
|
+
images = _images_from(command)
|
|
502
|
+
if self._session.is_disposed:
|
|
503
|
+
return _error(request_id, kind, _DISPOSED)
|
|
504
|
+
if self._session.is_compacting:
|
|
505
|
+
return _error(request_id, kind, _COMPACTING)
|
|
506
|
+
if self._is_busy():
|
|
507
|
+
behavior = command.get("streamingBehavior")
|
|
508
|
+
if behavior == "steer":
|
|
509
|
+
await self._session.steer(text, images)
|
|
510
|
+
return _success(request_id, kind, {"disposition": "queued"})
|
|
511
|
+
if behavior == "followUp":
|
|
512
|
+
await self._session.follow_up(text, images)
|
|
513
|
+
return _success(request_id, kind, {"disposition": "queued"})
|
|
514
|
+
return _error(request_id, kind, _BUSY)
|
|
515
|
+
self._start_run(text, images)
|
|
516
|
+
return _success(request_id, kind, {"disposition": "started"})
|
|
517
|
+
|
|
518
|
+
def _is_busy(self) -> bool:
|
|
519
|
+
"""是否已经有一次 run 在进行,或刚被接受但还没开始。
|
|
520
|
+
|
|
521
|
+
``is_streaming`` 由 Agent 在任务真正跑起来时才置位,而响应在起任务之后
|
|
522
|
+
立刻发出:两条 ``prompt`` 挨着到达时,第二条会看到 ``is_streaming`` 还是
|
|
523
|
+
``False``。只看它就会为同一条会话起两个 run,第二个必然在 Agent 里炸掉,
|
|
524
|
+
而客户端已经收到了 ``started``。
|
|
525
|
+
|
|
526
|
+
``_run_pending`` 补的正是"已接受、还没开始"这一段,由
|
|
527
|
+
:meth:`_on_run_done` 在任务收尾时清掉。整段 run 期间 ``is_streaming`` 为真,
|
|
528
|
+
所以清单里不会出现"两次都在跑"的判断依据重叠问题。
|
|
529
|
+
"""
|
|
530
|
+
return self._session.is_streaming or self._run_pending
|
|
531
|
+
|
|
532
|
+
async def _queue(
|
|
533
|
+
self, request_id: str | None, command: Mapping[str, JsonValue], kind: str
|
|
534
|
+
) -> JsonRecord:
|
|
535
|
+
"""``steer`` / ``follow_up``:只排队,不等回合边界。"""
|
|
536
|
+
text = _require_str(command, "message", kind)
|
|
537
|
+
images = _images_from(command)
|
|
538
|
+
if self._session.is_disposed:
|
|
539
|
+
return _error(request_id, kind, _DISPOSED)
|
|
540
|
+
disposition = (
|
|
541
|
+
await self._session.steer(text, images)
|
|
542
|
+
if kind == "steer"
|
|
543
|
+
else await self._session.follow_up(text, images)
|
|
544
|
+
)
|
|
545
|
+
return _success(request_id, kind, {"disposition": disposition})
|
|
546
|
+
|
|
547
|
+
async def _plan(self, request_id: str | None, command: Mapping[str, JsonValue]) -> JsonRecord:
|
|
548
|
+
"""``plan``:进入、批准或退出规划模式。
|
|
549
|
+
|
|
550
|
+
审批在这里是客户端的一次显式动作(``action: "approve"``),与模型无关:
|
|
551
|
+
协议层不提供"模型自己批准"的路径。计划正文本就在 ``plan_mode`` 事件与
|
|
552
|
+
``get_state.planMode`` 里,客户端不必再取一次。
|
|
553
|
+
"""
|
|
554
|
+
kind = "plan"
|
|
555
|
+
mode = self._session.plan_mode
|
|
556
|
+
if mode is None:
|
|
557
|
+
return _error(request_id, kind, "Session does not support plan mode")
|
|
558
|
+
action = command.get("action")
|
|
559
|
+
if action == "enter":
|
|
560
|
+
goal = command.get("goal")
|
|
561
|
+
state = await self._session.enter_plan_mode(goal if isinstance(goal, str) else "")
|
|
562
|
+
elif action == "approve":
|
|
563
|
+
state = await self._session.approve_plan()
|
|
564
|
+
elif action == "leave":
|
|
565
|
+
state = await self._session.leave_plan_mode()
|
|
566
|
+
else:
|
|
567
|
+
return _error(request_id, kind, f"Unknown plan action: {action}")
|
|
568
|
+
return _success(request_id, kind, {"planMode": state.to_wire()})
|
|
569
|
+
|
|
570
|
+
async def _set_model(
|
|
571
|
+
self, request_id: str | None, command: Mapping[str, JsonValue]
|
|
572
|
+
) -> JsonRecord:
|
|
573
|
+
"""切换模型。解析失败返回 ``Model not found: provider/id``。"""
|
|
574
|
+
kind = "set_model"
|
|
575
|
+
provider = _require_str(command, "provider", kind)
|
|
576
|
+
model_id = _require_str(command, "modelId", kind)
|
|
577
|
+
try:
|
|
578
|
+
await self._session.set_model(provider, model_id)
|
|
579
|
+
except ValueError:
|
|
580
|
+
return _error(request_id, kind, f"Model not found: {provider}/{model_id}")
|
|
581
|
+
return _success(request_id, kind, model_to_wire(self._session.model))
|
|
582
|
+
|
|
583
|
+
async def _set_thinking_level(
|
|
584
|
+
self, request_id: str | None, command: Mapping[str, JsonValue]
|
|
585
|
+
) -> JsonRecord:
|
|
586
|
+
"""设置思考级别。钳制交给会话层,响应只说"收到了"。"""
|
|
587
|
+
kind = "set_thinking_level"
|
|
588
|
+
level = _require_str(command, "level", kind)
|
|
589
|
+
if level not in _THINKING_LEVELS:
|
|
590
|
+
return _error(request_id, kind, f"Unknown thinking level: {level}")
|
|
591
|
+
await self._session.set_thinking_level(cast(ModelThinkingLevel, level))
|
|
592
|
+
return _success(request_id, kind)
|
|
593
|
+
|
|
594
|
+
async def _compact(
|
|
595
|
+
self, request_id: str | None, command: Mapping[str, JsonValue]
|
|
596
|
+
) -> JsonRecord:
|
|
597
|
+
"""手动压缩。压不动(会话太小/已压缩)是正常结果,用错误响应说清楚。"""
|
|
598
|
+
kind = "compact"
|
|
599
|
+
instructions = _opt_str(command, "customInstructions", kind)
|
|
600
|
+
try:
|
|
601
|
+
result = await self._session.compact(instructions)
|
|
602
|
+
except SummarizationError as exc:
|
|
603
|
+
return _error(request_id, kind, str(exc))
|
|
604
|
+
return _success(request_id, kind, compaction_result_to_wire(result))
|
|
605
|
+
|
|
606
|
+
# ---------------------------------------------------------------- 检查点
|
|
607
|
+
|
|
608
|
+
def _require_checkpoints(self) -> CheckpointStore:
|
|
609
|
+
"""检查点没启用时回一条明确的错误,不让客户端以为"撤销成功但什么都没变"。"""
|
|
610
|
+
checkpoints = self._session.checkpoints
|
|
611
|
+
if checkpoints is None:
|
|
612
|
+
raise _InvalidCommand("Checkpointing is disabled in this runtime")
|
|
613
|
+
return checkpoints
|
|
614
|
+
|
|
615
|
+
def _require_idle(self) -> None:
|
|
616
|
+
"""跑着的时候不许撤销。
|
|
617
|
+
|
|
618
|
+
模型可能正在写文件,此时把工作区拨回上一个回合,接下来的工具调用会落在
|
|
619
|
+
一个半新半旧的工作区上。撤销是一次全量恢复,必须独占。
|
|
620
|
+
"""
|
|
621
|
+
if self._is_busy():
|
|
622
|
+
raise _InvalidCommand("Cannot undo or redo while a run is in progress")
|
|
623
|
+
|
|
624
|
+
async def _undo(self, request_id: str | None, kind: str) -> JsonRecord:
|
|
625
|
+
self._require_idle()
|
|
626
|
+
try:
|
|
627
|
+
result = await self._require_checkpoints().undo()
|
|
628
|
+
except (CheckpointError, GitError) as exc:
|
|
629
|
+
return _error(request_id, kind, str(exc))
|
|
630
|
+
return _success(request_id, kind, undo_wire(result))
|
|
631
|
+
|
|
632
|
+
async def _redo(self, request_id: str | None, kind: str) -> JsonRecord:
|
|
633
|
+
self._require_idle()
|
|
634
|
+
try:
|
|
635
|
+
result = await self._require_checkpoints().redo()
|
|
636
|
+
except (CheckpointError, GitError) as exc:
|
|
637
|
+
return _error(request_id, kind, str(exc))
|
|
638
|
+
return _success(request_id, kind, undo_wire(result))
|
|
639
|
+
|
|
640
|
+
async def _get_diff(self, request_id: str | None, kind: str) -> JsonRecord:
|
|
641
|
+
try:
|
|
642
|
+
diff = await self._require_checkpoints().diff()
|
|
643
|
+
except (CheckpointError, GitError) as exc:
|
|
644
|
+
return _error(request_id, kind, str(exc))
|
|
645
|
+
return _success(request_id, kind, diff_wire(diff))
|
|
646
|
+
|
|
647
|
+
async def _new_session(
|
|
648
|
+
self, request_id: str | None, command: Mapping[str, JsonValue]
|
|
649
|
+
) -> JsonRecord:
|
|
650
|
+
"""换一个新会话:造新的 → 退订旧的 → 释放旧的 → 换指针 → 重新订阅。
|
|
651
|
+
|
|
652
|
+
先造后拆:新会话建不起来(磁盘、参数)时旧的原样还在,客户端拿到一条错误
|
|
653
|
+
响应就能继续用;反过来先拆再造,一次失败会让整个进程变成没有会话的壳。
|
|
654
|
+
"""
|
|
655
|
+
kind = "new_session"
|
|
656
|
+
if self._new_session_factory is None:
|
|
657
|
+
return _error(request_id, kind, "new_session is not supported in this runtime")
|
|
658
|
+
parent = _opt_str(command, "parentSession", kind)
|
|
659
|
+
current = self._session
|
|
660
|
+
replacement = await self._new_session_factory(current, parent)
|
|
661
|
+
self._deny_pending_permissions("会话已切换")
|
|
662
|
+
self._deny_pending_questions("会话已切换")
|
|
663
|
+
self._detach_events()
|
|
664
|
+
await current.dispose()
|
|
665
|
+
self._session = replacement
|
|
666
|
+
if self._stdout is not None:
|
|
667
|
+
self._unsubscribe = replacement.subscribe(self._on_event)
|
|
668
|
+
return _success(request_id, kind, {"cancelled": False})
|
|
669
|
+
|
|
670
|
+
# ---------------------------------------------------------------- 状态
|
|
671
|
+
|
|
672
|
+
def _state(self) -> JsonRecord:
|
|
673
|
+
"""``get_state`` 的数据体。
|
|
674
|
+
|
|
675
|
+
状态与用量数据合并进 ``get_state``:客户端一次查询就能拿到模型、上下文与
|
|
676
|
+
账单,既有字段一个不少。
|
|
677
|
+
"""
|
|
678
|
+
session = self._session
|
|
679
|
+
manager = session.session
|
|
680
|
+
settings = session.compaction_settings
|
|
681
|
+
state: JsonRecord = {
|
|
682
|
+
"model": model_to_wire(session.model),
|
|
683
|
+
"thinkingLevel": session.thinking_level,
|
|
684
|
+
"isStreaming": session.is_streaming,
|
|
685
|
+
"isCompacting": session.is_compacting,
|
|
686
|
+
"steeringMode": session.agent.steering_mode,
|
|
687
|
+
"followUpMode": session.agent.follow_up_mode,
|
|
688
|
+
"autoCompactionEnabled": bool(settings is not None and settings.enabled),
|
|
689
|
+
"messageCount": len(session.agent.state.messages),
|
|
690
|
+
"pendingMessageCount": len(session.get_steering_messages())
|
|
691
|
+
+ len(session.get_follow_up_messages()),
|
|
692
|
+
"sessionId": manager.get_session_id(),
|
|
693
|
+
}
|
|
694
|
+
state.update(status_wire_parts(session.context_status()))
|
|
695
|
+
plan = plan_wire(session.context_status())
|
|
696
|
+
if plan is not None:
|
|
697
|
+
state["plan"] = plan
|
|
698
|
+
plan_mode = plan_mode_wire(session.context_status())
|
|
699
|
+
if plan_mode is not None:
|
|
700
|
+
state["planMode"] = plan_mode
|
|
701
|
+
if session.checkpoints is not None:
|
|
702
|
+
state["checkpoint"] = checkpoint_wire(session.checkpoints)
|
|
703
|
+
session_file = manager.get_session_file()
|
|
704
|
+
if session_file is not None:
|
|
705
|
+
state["sessionFile"] = session_file
|
|
706
|
+
name = manager.get_session_name()
|
|
707
|
+
if name is not None:
|
|
708
|
+
state["sessionName"] = name
|
|
709
|
+
return state
|
|
710
|
+
|
|
711
|
+
def _mcp_statuses(self) -> Sequence[McpServerStatus]:
|
|
712
|
+
"""MCP 服务器状态快照;这次进程没接 MCP 时为空。"""
|
|
713
|
+
return () if self._mcp is None else tuple(self._mcp.statuses())
|
|
714
|
+
|
|
715
|
+
def _agents_state(self) -> JsonRecord:
|
|
716
|
+
"""子代理定义、运行参数与任务状态。客户端一次查询就能画出一个面板。"""
|
|
717
|
+
runtime = self._subagents
|
|
718
|
+
if runtime is None:
|
|
719
|
+
return {
|
|
720
|
+
"available": False,
|
|
721
|
+
"agents": [],
|
|
722
|
+
"tasks": [],
|
|
723
|
+
"settings": {},
|
|
724
|
+
"definitionDiagnostics": [],
|
|
725
|
+
}
|
|
726
|
+
return {
|
|
727
|
+
"available": True,
|
|
728
|
+
"agents": runtime.agents_wire(),
|
|
729
|
+
"tasks": runtime.tasks_wire(),
|
|
730
|
+
"settings": runtime.settings_wire(),
|
|
731
|
+
"definitionDiagnostics": runtime.diagnostics_wire(),
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
def _monitor_state(self) -> JsonRecord:
|
|
735
|
+
"""启动检查点、派生指标与后台任务。客户端按同一形状画监控面板。"""
|
|
736
|
+
return {
|
|
737
|
+
"monitor": (None if self._monitor is None else self._monitor.snapshot().wire()),
|
|
738
|
+
"tasks": [
|
|
739
|
+
_task_wire(task)
|
|
740
|
+
for task in (() if self._scheduler is None else self._scheduler.snapshot())
|
|
741
|
+
],
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
# ---------------------------------------------------------- 后台 run
|
|
745
|
+
|
|
746
|
+
def _start_run(self, text: str, images: Sequence[ImageContent] | None) -> None:
|
|
747
|
+
"""起一次 run 并立刻返回。响应由调用方发出,事件由订阅关系发出。"""
|
|
748
|
+
self._run_pending = True
|
|
749
|
+
task = asyncio.create_task(self._session.prompt(text, images=images))
|
|
750
|
+
self._run_tasks.add(task)
|
|
751
|
+
task.add_done_callback(self._on_run_done)
|
|
752
|
+
|
|
753
|
+
def _on_run_done(self, task: asyncio.Task[None]) -> None:
|
|
754
|
+
"""后台 run 的收尸:异常只进日志。
|
|
755
|
+
|
|
756
|
+
走到这里说明响应早就发出去了(``disposition: started``),所以没有"第二个
|
|
757
|
+
响应"可以发:接受之后的失败只能通过事件与消息表达。
|
|
758
|
+
"""
|
|
759
|
+
self._run_tasks.discard(task)
|
|
760
|
+
self._run_pending = False
|
|
761
|
+
if task.cancelled():
|
|
762
|
+
return
|
|
763
|
+
error = task.exception()
|
|
764
|
+
if error is not None:
|
|
765
|
+
logger.error("RPC prompt 失败: %s", error)
|
|
766
|
+
|
|
767
|
+
async def _drain_run_tasks(self) -> None:
|
|
768
|
+
if not self._run_tasks:
|
|
769
|
+
return
|
|
770
|
+
await asyncio.gather(*list(self._run_tasks), return_exceptions=True)
|
|
771
|
+
|
|
772
|
+
# ---------------------------------------------------------- 权限批准
|
|
773
|
+
|
|
774
|
+
async def request_approval(
|
|
775
|
+
self, prompt: PermissionPrompt, signal: CancelToken | None
|
|
776
|
+
) -> ApprovalAnswer:
|
|
777
|
+
"""写一条 ``permission_request``,等配对的 ``permission_response`` 命令。
|
|
778
|
+
|
|
779
|
+
``requestId`` 关联一次工具调用,命令的 ``id`` 关联一条客户端命令,
|
|
780
|
+
两者分开:服务端对命令仍按常规回 ``_success`` / ``_error``。
|
|
781
|
+
"""
|
|
782
|
+
del signal
|
|
783
|
+
if self._stdout is None or not self._client_online:
|
|
784
|
+
return ApprovalAnswer(scope="deny", note="RPC 客户端不在线")
|
|
785
|
+
request = prompt.request
|
|
786
|
+
self._permission_counter += 1
|
|
787
|
+
request_id = f"permission-{self._permission_counter}"
|
|
788
|
+
future: asyncio.Future[ApprovalAnswer] = asyncio.get_running_loop().create_future()
|
|
789
|
+
self._pending_permissions[request_id] = _PendingPermission(
|
|
790
|
+
future=future, tool=request.tool_name
|
|
791
|
+
)
|
|
792
|
+
await self._emit(
|
|
793
|
+
{
|
|
794
|
+
"type": "permission_request",
|
|
795
|
+
"requestId": request_id,
|
|
796
|
+
"tool": request.tool_name,
|
|
797
|
+
"toolCallId": request.tool_call_id,
|
|
798
|
+
"args": dict(request.args),
|
|
799
|
+
"reason": prompt.reason,
|
|
800
|
+
"rule": prompt.rule,
|
|
801
|
+
"mode": prompt.mode,
|
|
802
|
+
"options": list(prompt.options),
|
|
803
|
+
"proposal": (
|
|
804
|
+
None
|
|
805
|
+
if prompt.proposal is None
|
|
806
|
+
else {
|
|
807
|
+
"table": prompt.proposal.table,
|
|
808
|
+
"pattern": prompt.proposal.pattern,
|
|
809
|
+
}
|
|
810
|
+
),
|
|
811
|
+
}
|
|
812
|
+
)
|
|
813
|
+
try:
|
|
814
|
+
return await future
|
|
815
|
+
finally:
|
|
816
|
+
self._pending_permissions.pop(request_id, None)
|
|
817
|
+
|
|
818
|
+
async def _permission_response(
|
|
819
|
+
self, request_id: str | None, command: Mapping[str, JsonValue]
|
|
820
|
+
) -> JsonRecord:
|
|
821
|
+
kind = "permission_response"
|
|
822
|
+
target = _require_str(command, "requestId", kind)
|
|
823
|
+
scope = _require_str(command, "scope", kind)
|
|
824
|
+
if scope not in APPROVAL_SCOPES:
|
|
825
|
+
raise _InvalidCommand(f"Unknown permission scope: {scope}")
|
|
826
|
+
pending = self._pending_permissions.get(target)
|
|
827
|
+
if pending is None or pending.future.done():
|
|
828
|
+
return _error(request_id, kind, f"Unknown or settled permission request: {target}")
|
|
829
|
+
pending.future.set_result(ApprovalAnswer(scope=scope))
|
|
830
|
+
await self._emit(
|
|
831
|
+
{
|
|
832
|
+
"type": "permission_response",
|
|
833
|
+
"requestId": target,
|
|
834
|
+
"scope": scope,
|
|
835
|
+
"tool": pending.tool,
|
|
836
|
+
"accepted": True,
|
|
837
|
+
}
|
|
838
|
+
)
|
|
839
|
+
return _success(request_id, kind, {"requestId": target, "scope": scope})
|
|
840
|
+
|
|
841
|
+
def _deny_pending_permissions(self, note: str) -> None:
|
|
842
|
+
"""客户端离线、运行被取消或会话切换时,把挂起请求全部收成拒绝。"""
|
|
843
|
+
for pending in self._pending_permissions.values():
|
|
844
|
+
if not pending.future.done():
|
|
845
|
+
pending.future.set_result(ApprovalAnswer(scope="deny", note=note))
|
|
846
|
+
|
|
847
|
+
# ---------------------------------------------------------- 提问通道
|
|
848
|
+
|
|
849
|
+
async def request_question(
|
|
850
|
+
self, request: QuestionRequest, signal: CancelToken | None
|
|
851
|
+
) -> QuestionAnswer:
|
|
852
|
+
"""写一条 ``question_request``,等配对的 ``question_response`` 命令。
|
|
853
|
+
|
|
854
|
+
``requestId`` 形如 ``question-N``,与权限请求的编号空间分开:两类请求可以
|
|
855
|
+
同时挂起,客户端不必区分"下一个回应谁"——按 ``requestId`` 配对就够了。
|
|
856
|
+
"""
|
|
857
|
+
del signal
|
|
858
|
+
if self._stdout is None or not self._client_online:
|
|
859
|
+
return QuestionAnswer(cancelled=True)
|
|
860
|
+
self._question_counter += 1
|
|
861
|
+
request_id = f"question-{self._question_counter}"
|
|
862
|
+
future: asyncio.Future[QuestionAnswer] = asyncio.get_running_loop().create_future()
|
|
863
|
+
self._pending_questions[request_id] = _PendingQuestion(
|
|
864
|
+
future=future, question=request.question
|
|
865
|
+
)
|
|
866
|
+
await self._emit(
|
|
867
|
+
{
|
|
868
|
+
"type": "question_request",
|
|
869
|
+
"requestId": request_id,
|
|
870
|
+
"question": request.question,
|
|
871
|
+
"header": request.header,
|
|
872
|
+
"options": [
|
|
873
|
+
{"label": option.label, "description": option.description}
|
|
874
|
+
for option in request.options
|
|
875
|
+
],
|
|
876
|
+
"multiple": request.multiple,
|
|
877
|
+
}
|
|
878
|
+
)
|
|
879
|
+
try:
|
|
880
|
+
return await future
|
|
881
|
+
finally:
|
|
882
|
+
self._pending_questions.pop(request_id, None)
|
|
883
|
+
|
|
884
|
+
async def _question_response(
|
|
885
|
+
self, request_id: str | None, command: Mapping[str, JsonValue]
|
|
886
|
+
) -> JsonRecord:
|
|
887
|
+
"""接收客户端对一次提问的回答。
|
|
888
|
+
|
|
889
|
+
``selected`` / ``custom`` 都缺省时按取消处理——与 REPL 的空行语义一致,
|
|
890
|
+
工具会把取消折成 ``is_error`` 结果并提示模型采用默认假设。
|
|
891
|
+
"""
|
|
892
|
+
kind = "question_response"
|
|
893
|
+
target = _require_str(command, "requestId", kind)
|
|
894
|
+
raw_selected = command.get("selected")
|
|
895
|
+
selected: list[str] = []
|
|
896
|
+
if raw_selected is not None:
|
|
897
|
+
if not isinstance(raw_selected, list) or not all(
|
|
898
|
+
isinstance(item, str) for item in raw_selected
|
|
899
|
+
):
|
|
900
|
+
raise _InvalidCommand("'selected' must be an array of strings")
|
|
901
|
+
selected = [item for item in raw_selected if isinstance(item, str)]
|
|
902
|
+
custom = _opt_str(command, "custom", kind) or ""
|
|
903
|
+
pending = self._pending_questions.get(target)
|
|
904
|
+
if pending is None or pending.future.done():
|
|
905
|
+
return _error(request_id, kind, f"Unknown or settled question request: {target}")
|
|
906
|
+
answer = (
|
|
907
|
+
QuestionAnswer(selected=tuple(selected), custom=custom)
|
|
908
|
+
if selected or custom
|
|
909
|
+
else QuestionAnswer(cancelled=True)
|
|
910
|
+
)
|
|
911
|
+
pending.future.set_result(answer)
|
|
912
|
+
await self._emit(
|
|
913
|
+
{
|
|
914
|
+
"type": "question_response",
|
|
915
|
+
"requestId": target,
|
|
916
|
+
"selected": selected,
|
|
917
|
+
"custom": custom,
|
|
918
|
+
"cancelled": answer.cancelled,
|
|
919
|
+
}
|
|
920
|
+
)
|
|
921
|
+
return _success(request_id, kind, {"requestId": target, "cancelled": answer.cancelled})
|
|
922
|
+
|
|
923
|
+
def _deny_pending_questions(self, note: str) -> None:
|
|
924
|
+
"""与权限同一套收尾:提问没有回答来源时按取消处理。"""
|
|
925
|
+
del note # 取消没有原因字段:对模型来说"用户没有回答"就是全部信息。
|
|
926
|
+
for pending in self._pending_questions.values():
|
|
927
|
+
if not pending.future.done():
|
|
928
|
+
pending.future.set_result(QuestionAnswer(cancelled=True))
|
|
929
|
+
|
|
930
|
+
# ---------------------------------------------------------------- 输出
|
|
931
|
+
|
|
932
|
+
async def _on_event(self, event: SessionEvent) -> None:
|
|
933
|
+
"""会话事件 → 一条 JSONL。
|
|
934
|
+
|
|
935
|
+
这里写成协程:``AgentSession`` 会 ``await`` 监听器,于是 stdout 写得慢就
|
|
936
|
+
等于模型跑得慢,反压因此传回模型。
|
|
937
|
+
另起一个任务转发会把顺序交给调度器(事件乱序落盘),反压也随之消失。
|
|
938
|
+
"""
|
|
939
|
+
if self._stdout is None:
|
|
940
|
+
return
|
|
941
|
+
await self._emit(session_event_to_wire(event))
|
|
942
|
+
|
|
943
|
+
async def _emit(self, record: JsonRecord) -> None:
|
|
944
|
+
"""写一条记录。加锁保证"一次写 = 一整行"——事件与响应会交错到达这里。"""
|
|
945
|
+
stdout = self._stdout
|
|
946
|
+
lock = self._write_lock
|
|
947
|
+
if stdout is None or lock is None:
|
|
948
|
+
raise RuntimeError("RpcServer 未在运行,无法写出记录")
|
|
949
|
+
async with lock:
|
|
950
|
+
await stdout(record)
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
__all__ = ["JsonRecord", "NewSessionFn", "RpcServer", "Stdout", "iter_json_lines"]
|