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,530 @@
|
|
|
1
|
+
"""一个活着的会话:事件缓冲、SSE 订阅者、批准与提问通道。
|
|
2
|
+
|
|
3
|
+
HTTP 服务与 RPC 的区别在于"一个进程里活着多个会话、每个会话可以有多个客户端"。
|
|
4
|
+
这带来三件 RPC 不需要处理的事:
|
|
5
|
+
|
|
6
|
+
1. **事件要编号并留一段历史。** 客户端断线重连时带 ``Last-Event-ID``,服务端从缓冲
|
|
7
|
+
里补发;没有编号与缓冲,断一次就得重新拉全量状态。
|
|
8
|
+
2. **订阅者不能反压模型。** RPC 的写出是 ``await`` 的,慢客户端会让模型一起慢;
|
|
9
|
+
HTTP 有多个客户端,一个卡住的浏览器不能拖住其他人和 Agent。所以每个订阅者一个
|
|
10
|
+
有界队列,队列满了就断开这个订阅者。
|
|
11
|
+
3. **批准与提问要能被"当前不在线"的客户端回答。** 请求先作为事件进入同一条流,
|
|
12
|
+
客户端发 HTTP 请求回答;服务端不假设自己知道谁在听。
|
|
13
|
+
|
|
14
|
+
阻塞当前正在运行的会话为空闲之后才允许下一次 prompt,这一点与 RPC 一致:并发两次
|
|
15
|
+
run 会让同一个转录被两个循环同时写。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import contextlib
|
|
22
|
+
import json
|
|
23
|
+
import queue
|
|
24
|
+
from collections import deque
|
|
25
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Final
|
|
28
|
+
|
|
29
|
+
from braid_ai.cancel import CancelToken
|
|
30
|
+
from braid_ai.types import AssistantMessage, ImageContent, JsonValue
|
|
31
|
+
from braid_coding_agent.modes.json_mode import (
|
|
32
|
+
session_event_to_wire,
|
|
33
|
+
transcript_message_to_wire,
|
|
34
|
+
)
|
|
35
|
+
from braid_coding_agent.permissions.engine import (
|
|
36
|
+
ApprovalAnswer,
|
|
37
|
+
ApprovalScope,
|
|
38
|
+
PermissionPrompt,
|
|
39
|
+
)
|
|
40
|
+
from braid_coding_agent.questions import QuestionAnswer, QuestionRequest
|
|
41
|
+
from braid_coding_agent.session.agent_session import AgentSession, SessionEvent
|
|
42
|
+
|
|
43
|
+
from .errors import conflict, not_found
|
|
44
|
+
from .router import Frame
|
|
45
|
+
|
|
46
|
+
__all__ = ["SessionHub", "Subscription"]
|
|
47
|
+
|
|
48
|
+
#: 每个会话保留的事件条数。够覆盖一次断线重连,又不至于让一个长会话吃满内存。
|
|
49
|
+
BUFFER_SIZE: Final[int] = 1000
|
|
50
|
+
|
|
51
|
+
#: 每个订阅者的待发队列上限。满了说明客户端已经不读了,断开它。
|
|
52
|
+
SUBSCRIBER_QUEUE_SIZE: Final[int] = 512
|
|
53
|
+
|
|
54
|
+
#: SSE 心跳间隔(秒)。中间设备会在长时间无数据时掐掉连接。
|
|
55
|
+
KEEPALIVE_SECONDS: Final[float] = 15.0
|
|
56
|
+
|
|
57
|
+
#: 一条提问等客户端回答的上限(秒)。HTTP 没有"连接还在不在"这个信号,
|
|
58
|
+
#: 一个走掉的客户端会让 run 永远停在一个 `await` 上。
|
|
59
|
+
QUESTION_TIMEOUT_SECONDS: Final[float] = 300.0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(slots=True, frozen=True)
|
|
63
|
+
class Subscription:
|
|
64
|
+
"""一个 SSE 订阅者。
|
|
65
|
+
|
|
66
|
+
``queue`` 里放的是已经带 ``seq`` 的事件 dict;``None`` 是"服务端让你断开"的
|
|
67
|
+
哨兵(队列溢出或会话关闭)。
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
id: int
|
|
71
|
+
queue: queue.Queue[dict[str, JsonValue] | None]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _seq_of(event: Mapping[str, JsonValue]) -> int:
|
|
75
|
+
"""事件里的序号。缺字段按 0 处理——补发比较不该因为一条坏记录崩掉。"""
|
|
76
|
+
raw = event.get("seq")
|
|
77
|
+
return raw if isinstance(raw, int) else 0
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(slots=True)
|
|
81
|
+
class _PendingPermission:
|
|
82
|
+
"""等待客户端回答的一条权限请求。"""
|
|
83
|
+
|
|
84
|
+
future: asyncio.Future[ApprovalAnswer]
|
|
85
|
+
tool: str
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(slots=True)
|
|
89
|
+
class _PendingQuestion:
|
|
90
|
+
"""等待客户端回答的一条提问。"""
|
|
91
|
+
|
|
92
|
+
future: asyncio.Future[QuestionAnswer]
|
|
93
|
+
question: str
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class SessionHub:
|
|
97
|
+
"""一个会话的服务端外壳。
|
|
98
|
+
|
|
99
|
+
所有公开方法都必须在会话所属的事件循环上调用;SSE 的读线程通过
|
|
100
|
+
:meth:`subscription_frames` 拿数据,那条路径只碰线程安全的 ``queue.Queue``。
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
session: AgentSession,
|
|
106
|
+
*,
|
|
107
|
+
buffer_size: int = BUFFER_SIZE,
|
|
108
|
+
question_timeout: float = QUESTION_TIMEOUT_SECONDS,
|
|
109
|
+
) -> None:
|
|
110
|
+
self.session = session
|
|
111
|
+
self._events: deque[dict[str, JsonValue]] = deque(maxlen=buffer_size)
|
|
112
|
+
self._seq = 0
|
|
113
|
+
self._subscribers: dict[int, queue.Queue[dict[str, JsonValue] | None]] = {}
|
|
114
|
+
self._next_subscriber = 0
|
|
115
|
+
self._run_task: asyncio.Task[None] | None = None
|
|
116
|
+
self._unsubscribe: Callable[[], None] | None = None
|
|
117
|
+
self._pending_permissions: dict[str, _PendingPermission] = {}
|
|
118
|
+
self._permission_counter = 0
|
|
119
|
+
self._pending_questions: dict[str, _PendingQuestion] = {}
|
|
120
|
+
self._question_counter = 0
|
|
121
|
+
self._question_timeout = question_timeout
|
|
122
|
+
self._closed = False
|
|
123
|
+
self._loop: asyncio.AbstractEventLoop | None = None
|
|
124
|
+
|
|
125
|
+
# ---------------------------------------------------------------- 生命周期
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def session_id(self) -> str:
|
|
129
|
+
return self.session.session.get_session_id()
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def seq(self) -> int:
|
|
133
|
+
"""已经发布的最大事件序号。``0`` 表示这个会话还没有产生任何事件。"""
|
|
134
|
+
return self._seq
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def is_busy(self) -> bool:
|
|
138
|
+
"""是否有一次 run 正在进行(或刚被接受)。"""
|
|
139
|
+
running = self._run_task is not None and not self._run_task.done()
|
|
140
|
+
return running or self.session.is_streaming
|
|
141
|
+
|
|
142
|
+
def start(self) -> None:
|
|
143
|
+
"""订阅会话事件。必须在事件循环上调用,且只调用一次。"""
|
|
144
|
+
if self._closed:
|
|
145
|
+
raise RuntimeError("会话已经关闭")
|
|
146
|
+
self._loop = asyncio.get_running_loop()
|
|
147
|
+
self._unsubscribe = self.session.subscribe(self._on_event)
|
|
148
|
+
|
|
149
|
+
async def close(self) -> None:
|
|
150
|
+
"""取消运行、释放会话、通知订阅者断开。幂等。
|
|
151
|
+
|
|
152
|
+
走 ``dispose()`` 而不是自己 abort:会话文件的跨进程锁、工具输出目录与
|
|
153
|
+
``agent_settled`` 的收尾都在那里。服务端多会话共用一份 MCP 运行时,
|
|
154
|
+
那边的 ``session_shutdown`` 关闭行为由运行时自己的开关控制。
|
|
155
|
+
"""
|
|
156
|
+
if self._closed:
|
|
157
|
+
return
|
|
158
|
+
self._closed = True
|
|
159
|
+
self._deny_pending_permissions("会话已关闭")
|
|
160
|
+
self._cancel_pending_questions()
|
|
161
|
+
await self.session.dispose()
|
|
162
|
+
self._run_task = None
|
|
163
|
+
for token in list(self._subscribers.values()):
|
|
164
|
+
token.put(None)
|
|
165
|
+
self._subscribers.clear()
|
|
166
|
+
if self._unsubscribe is not None:
|
|
167
|
+
self._unsubscribe()
|
|
168
|
+
self._unsubscribe = None
|
|
169
|
+
|
|
170
|
+
# ------------------------------------------------------------------ 事件
|
|
171
|
+
|
|
172
|
+
def publish(self, record: dict[str, JsonValue]) -> dict[str, JsonValue]:
|
|
173
|
+
"""给一条事件编号、入缓冲、投递给全部订阅者。
|
|
174
|
+
|
|
175
|
+
``record`` 不能已经带 ``seq``:序号由这里唯一分配,客户端按它排序与续传。
|
|
176
|
+
"""
|
|
177
|
+
self._seq += 1
|
|
178
|
+
event: dict[str, JsonValue] = {"seq": self._seq, **record}
|
|
179
|
+
self._events.append(event)
|
|
180
|
+
for token in list(self._subscribers.values()):
|
|
181
|
+
try:
|
|
182
|
+
token.put_nowait(event)
|
|
183
|
+
except queue.Full:
|
|
184
|
+
# 客户端不读了:断开它,别让一条卡住的连接拖住整个会话。
|
|
185
|
+
self._drop_subscriber(token)
|
|
186
|
+
return event
|
|
187
|
+
|
|
188
|
+
async def _on_event(self, event: SessionEvent) -> None:
|
|
189
|
+
"""会话事件 → 一条带序号的 wire 记录。
|
|
190
|
+
|
|
191
|
+
同步完成,不 ``await`` 任何 I/O:这里的耗时就是模型的耗时。
|
|
192
|
+
"""
|
|
193
|
+
self.publish(session_event_to_wire(event))
|
|
194
|
+
|
|
195
|
+
def subscribe(self, since: int | None = None) -> Subscription:
|
|
196
|
+
"""注册一个订阅者,可选地补发 ``since`` 之后的事件。
|
|
197
|
+
|
|
198
|
+
补发与注册都在事件循环上完成,所以中间不会被新事件插队:客户端看到的顺序
|
|
199
|
+
一定是序号顺序。
|
|
200
|
+
|
|
201
|
+
:raises ValueError: ``since`` 早于缓冲区最旧的一条,补不齐。
|
|
202
|
+
"""
|
|
203
|
+
self._next_subscriber += 1
|
|
204
|
+
token: queue.Queue[dict[str, JsonValue] | None] = queue.Queue(maxsize=SUBSCRIBER_QUEUE_SIZE)
|
|
205
|
+
if since is not None:
|
|
206
|
+
oldest, _ = self.buffered
|
|
207
|
+
if oldest and since < oldest - 1:
|
|
208
|
+
raise ValueError(f"事件 {since} 已经不在缓冲里")
|
|
209
|
+
for event in self._events:
|
|
210
|
+
if _seq_of(event) > since:
|
|
211
|
+
token.put_nowait(event)
|
|
212
|
+
self._subscribers[self._next_subscriber] = token
|
|
213
|
+
return Subscription(id=self._next_subscriber, queue=token)
|
|
214
|
+
|
|
215
|
+
def unsubscribe(self, subscription: Subscription) -> None:
|
|
216
|
+
"""移除订阅者。SSE 线程读到断开会话之后调用它。"""
|
|
217
|
+
self._subscribers.pop(subscription.id, None)
|
|
218
|
+
|
|
219
|
+
def _drop_subscriber(self, token: queue.Queue[dict[str, JsonValue] | None]) -> None:
|
|
220
|
+
"""摘掉一个订阅者,并保证它一定能读到"断开"哨兵。
|
|
221
|
+
|
|
222
|
+
队列已满时先挤掉一条再放哨兵:否则 ``put_nowait(None)`` 会再次失败,读线程
|
|
223
|
+
永远等不到结束信号,连接就一直挂着收心跳。
|
|
224
|
+
"""
|
|
225
|
+
for key, existing in list(self._subscribers.items()):
|
|
226
|
+
if existing is token:
|
|
227
|
+
del self._subscribers[key]
|
|
228
|
+
if token.full():
|
|
229
|
+
with contextlib.suppress(queue.Empty):
|
|
230
|
+
token.get_nowait()
|
|
231
|
+
with contextlib.suppress(queue.Full):
|
|
232
|
+
token.put_nowait(None)
|
|
233
|
+
|
|
234
|
+
@property
|
|
235
|
+
def buffered(self) -> tuple[int, int]:
|
|
236
|
+
"""``(最旧序号, 最新序号)``。空缓冲返回 ``(0, 0)``。
|
|
237
|
+
|
|
238
|
+
最旧序号按"最新序号减缓冲长度"算:``deque`` 的 ``maxlen`` 一到就会挤掉
|
|
239
|
+
最旧的一条,序号本身单调递增,不需要额外记账。
|
|
240
|
+
"""
|
|
241
|
+
if not self._events:
|
|
242
|
+
return (0, 0)
|
|
243
|
+
return (self._seq - len(self._events) + 1, self._seq)
|
|
244
|
+
|
|
245
|
+
def subscription_frames(
|
|
246
|
+
self, subscription: Subscription, keepalive: float = KEEPALIVE_SECONDS
|
|
247
|
+
) -> tuple[list[Frame], bool]:
|
|
248
|
+
"""从订阅队列取下一批帧,最多等 ``keepalive`` 秒。
|
|
249
|
+
|
|
250
|
+
返回 ``(帧列表, 是否要断开)``。空列表表示该发一次心跳(连接还活着,只是
|
|
251
|
+
没有事件)。这个方法只在 SSE 读线程里调用。
|
|
252
|
+
"""
|
|
253
|
+
frames: list[Frame] = []
|
|
254
|
+
closed = False
|
|
255
|
+
try:
|
|
256
|
+
first = subscription.queue.get(timeout=keepalive)
|
|
257
|
+
except queue.Empty:
|
|
258
|
+
return frames, False
|
|
259
|
+
batch: list[dict[str, JsonValue] | None] = [first]
|
|
260
|
+
while True:
|
|
261
|
+
try:
|
|
262
|
+
batch.append(subscription.queue.get_nowait())
|
|
263
|
+
except queue.Empty:
|
|
264
|
+
break
|
|
265
|
+
for event in batch:
|
|
266
|
+
if event is None:
|
|
267
|
+
closed = True
|
|
268
|
+
continue
|
|
269
|
+
data = json.dumps(event, ensure_ascii=False)
|
|
270
|
+
frames.append(
|
|
271
|
+
Frame(
|
|
272
|
+
id=str(event.get("seq", "")),
|
|
273
|
+
event=str(event.get("type", "message")),
|
|
274
|
+
data=data,
|
|
275
|
+
)
|
|
276
|
+
)
|
|
277
|
+
return frames, closed
|
|
278
|
+
|
|
279
|
+
# -------------------------------------------------------------- 运行控制
|
|
280
|
+
|
|
281
|
+
async def prompt(
|
|
282
|
+
self,
|
|
283
|
+
text: str,
|
|
284
|
+
*,
|
|
285
|
+
images: Sequence[ImageContent] | None = None,
|
|
286
|
+
behavior: str = "prompt",
|
|
287
|
+
wait: bool = False,
|
|
288
|
+
) -> JsonValue:
|
|
289
|
+
"""提交一次输入。
|
|
290
|
+
|
|
291
|
+
``behavior`` 决定它走哪条路:``prompt`` 起一次新 run,``steer`` /
|
|
292
|
+
``followUp`` 在当前 run 里排队。``wait`` 为真时等到 ``agent_settled``,
|
|
293
|
+
返回最后一条助手消息。
|
|
294
|
+
"""
|
|
295
|
+
if self._closed:
|
|
296
|
+
raise conflict("会话已关闭")
|
|
297
|
+
if behavior in ("steer", "followUp"):
|
|
298
|
+
if not self.is_busy:
|
|
299
|
+
raise conflict(f"没有正在运行的回合,{behavior} 无处可排队")
|
|
300
|
+
disposition = (
|
|
301
|
+
await self.session.steer(text, images)
|
|
302
|
+
if behavior == "steer"
|
|
303
|
+
else await self.session.follow_up(text, images)
|
|
304
|
+
)
|
|
305
|
+
return {"disposition": "queued", "mode": disposition}
|
|
306
|
+
if behavior != "prompt":
|
|
307
|
+
raise conflict(f"未知的 behavior: {behavior}")
|
|
308
|
+
if self.is_busy:
|
|
309
|
+
raise conflict(
|
|
310
|
+
"会话正在运行;用 behavior=steer 或 behavior=followUp 排队,或先 abort",
|
|
311
|
+
busy=True,
|
|
312
|
+
)
|
|
313
|
+
task = asyncio.create_task(self.session.prompt(text, images=images))
|
|
314
|
+
self._run_task = task
|
|
315
|
+
task.add_done_callback(self._on_run_done)
|
|
316
|
+
if not wait:
|
|
317
|
+
return {"disposition": "started"}
|
|
318
|
+
await asyncio.shield(task)
|
|
319
|
+
message = self._last_assistant_message()
|
|
320
|
+
return {
|
|
321
|
+
"disposition": "completed",
|
|
322
|
+
"message": transcript_message_to_wire(message) if message is not None else None,
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
def _on_run_done(self, task: asyncio.Task[None]) -> None:
|
|
326
|
+
"""后台 run 收尾:异常已经在会话层折成错误消息,这里只清指针。"""
|
|
327
|
+
if self._run_task is task:
|
|
328
|
+
self._run_task = None
|
|
329
|
+
if task.cancelled():
|
|
330
|
+
return
|
|
331
|
+
error = task.exception()
|
|
332
|
+
if error is not None:
|
|
333
|
+
self.publish({"type": "server_error", "message": str(error)})
|
|
334
|
+
|
|
335
|
+
def _last_assistant_message(self) -> AssistantMessage | None:
|
|
336
|
+
for message in reversed(self.session.agent.state.messages):
|
|
337
|
+
if isinstance(message, AssistantMessage):
|
|
338
|
+
return message
|
|
339
|
+
return None
|
|
340
|
+
|
|
341
|
+
async def abort(self) -> None:
|
|
342
|
+
"""取消当前 run。没有 run 时也返回成功:客户端重试 abort 不该报错。"""
|
|
343
|
+
self._deny_pending_permissions("运行被取消")
|
|
344
|
+
self._cancel_pending_questions()
|
|
345
|
+
await self.session.abort()
|
|
346
|
+
task = self._run_task
|
|
347
|
+
if task is not None and not task.done():
|
|
348
|
+
await asyncio.gather(task, return_exceptions=True)
|
|
349
|
+
|
|
350
|
+
# ------------------------------------------------------------- 权限通道
|
|
351
|
+
|
|
352
|
+
async def request_approval(
|
|
353
|
+
self, prompt: PermissionPrompt, signal: CancelToken | None
|
|
354
|
+
) -> ApprovalAnswer:
|
|
355
|
+
"""把一次批准请求发成事件,等客户端通过 HTTP 回答。
|
|
356
|
+
|
|
357
|
+
请求超时由权限引擎控制(``approval_timeout_seconds``);这里只负责在
|
|
358
|
+
任何退出路径上把挂起项清掉,不留一个永远不醒的 Future。
|
|
359
|
+
"""
|
|
360
|
+
del signal
|
|
361
|
+
if self._closed:
|
|
362
|
+
return ApprovalAnswer(scope="deny", note="会话已关闭")
|
|
363
|
+
self._permission_counter += 1
|
|
364
|
+
request_id = f"permission-{self._permission_counter}"
|
|
365
|
+
future: asyncio.Future[ApprovalAnswer] = asyncio.get_running_loop().create_future()
|
|
366
|
+
request = prompt.request
|
|
367
|
+
self._pending_permissions[request_id] = _PendingPermission(
|
|
368
|
+
future=future, tool=request.tool_name
|
|
369
|
+
)
|
|
370
|
+
self.publish(
|
|
371
|
+
{
|
|
372
|
+
"type": "permission_request",
|
|
373
|
+
"requestId": request_id,
|
|
374
|
+
"tool": request.tool_name,
|
|
375
|
+
"toolCallId": request.tool_call_id,
|
|
376
|
+
"args": dict(request.args),
|
|
377
|
+
"reason": prompt.reason,
|
|
378
|
+
"rule": prompt.rule,
|
|
379
|
+
"mode": prompt.mode,
|
|
380
|
+
"options": list(prompt.options),
|
|
381
|
+
"proposal": (
|
|
382
|
+
None
|
|
383
|
+
if prompt.proposal is None
|
|
384
|
+
else {
|
|
385
|
+
"table": prompt.proposal.table,
|
|
386
|
+
"pattern": prompt.proposal.pattern,
|
|
387
|
+
}
|
|
388
|
+
),
|
|
389
|
+
}
|
|
390
|
+
)
|
|
391
|
+
try:
|
|
392
|
+
return await future
|
|
393
|
+
except asyncio.CancelledError:
|
|
394
|
+
self.publish(
|
|
395
|
+
{
|
|
396
|
+
"type": "permission_response",
|
|
397
|
+
"requestId": request_id,
|
|
398
|
+
"scope": "deny",
|
|
399
|
+
"tool": request.tool_name,
|
|
400
|
+
"accepted": False,
|
|
401
|
+
}
|
|
402
|
+
)
|
|
403
|
+
raise
|
|
404
|
+
finally:
|
|
405
|
+
self._pending_permissions.pop(request_id, None)
|
|
406
|
+
|
|
407
|
+
def answer_permission(self, request_id: str, scope: ApprovalScope) -> JsonValue:
|
|
408
|
+
"""客户端回答一次批准请求。未知 id 返回 404,已结算的同样返回 404。"""
|
|
409
|
+
pending = self._pending_permissions.get(request_id)
|
|
410
|
+
if pending is None or pending.future.done():
|
|
411
|
+
raise not_found(f"没有挂起的权限请求: {request_id}")
|
|
412
|
+
pending.future.set_result(ApprovalAnswer(scope=scope))
|
|
413
|
+
self.publish(
|
|
414
|
+
{
|
|
415
|
+
"type": "permission_response",
|
|
416
|
+
"requestId": request_id,
|
|
417
|
+
"scope": scope,
|
|
418
|
+
"tool": pending.tool,
|
|
419
|
+
"accepted": scope != "deny",
|
|
420
|
+
}
|
|
421
|
+
)
|
|
422
|
+
return {"requestId": request_id, "scope": scope}
|
|
423
|
+
|
|
424
|
+
def pending_permissions(self) -> list[JsonValue]:
|
|
425
|
+
"""当前挂起的权限请求。客户端重连后据此补画批准界面。"""
|
|
426
|
+
return [
|
|
427
|
+
{"requestId": request_id, "tool": pending.tool}
|
|
428
|
+
for request_id, pending in self._pending_permissions.items()
|
|
429
|
+
if not pending.future.done()
|
|
430
|
+
]
|
|
431
|
+
|
|
432
|
+
def _deny_pending_permissions(self, note: str) -> None:
|
|
433
|
+
for pending in self._pending_permissions.values():
|
|
434
|
+
if not pending.future.done():
|
|
435
|
+
pending.future.set_result(ApprovalAnswer(scope="deny", note=note))
|
|
436
|
+
|
|
437
|
+
# ------------------------------------------------------------- 提问通道
|
|
438
|
+
|
|
439
|
+
async def request_question(
|
|
440
|
+
self, request: QuestionRequest, signal: CancelToken | None
|
|
441
|
+
) -> QuestionAnswer:
|
|
442
|
+
"""把一次提问发成事件,等客户端回答。取消、超时、会话关闭都按"没有回答"收尾。
|
|
443
|
+
|
|
444
|
+
超时是 HTTP 特有的:RPC 能靠"客户端离线"判定,HTTP 没有一条常驻连接可以
|
|
445
|
+
依赖。没有超时,一个走掉的客户端会让整个 run 停在 `await` 上。
|
|
446
|
+
"""
|
|
447
|
+
del signal
|
|
448
|
+
if self._closed:
|
|
449
|
+
return QuestionAnswer(cancelled=True)
|
|
450
|
+
self._question_counter += 1
|
|
451
|
+
request_id = f"question-{self._question_counter}"
|
|
452
|
+
future: asyncio.Future[QuestionAnswer] = asyncio.get_running_loop().create_future()
|
|
453
|
+
self._pending_questions[request_id] = _PendingQuestion(
|
|
454
|
+
future=future, question=request.question
|
|
455
|
+
)
|
|
456
|
+
self.publish(
|
|
457
|
+
{
|
|
458
|
+
"type": "question_request",
|
|
459
|
+
"requestId": request_id,
|
|
460
|
+
"question": request.question,
|
|
461
|
+
"header": request.header,
|
|
462
|
+
"options": [
|
|
463
|
+
{"label": option.label, "description": option.description}
|
|
464
|
+
for option in request.options
|
|
465
|
+
],
|
|
466
|
+
"multiple": request.multiple,
|
|
467
|
+
}
|
|
468
|
+
)
|
|
469
|
+
try:
|
|
470
|
+
return await asyncio.wait_for(future, timeout=self._question_timeout)
|
|
471
|
+
except TimeoutError:
|
|
472
|
+
self.publish(
|
|
473
|
+
{
|
|
474
|
+
"type": "question_response",
|
|
475
|
+
"requestId": request_id,
|
|
476
|
+
"selected": [],
|
|
477
|
+
"custom": "",
|
|
478
|
+
"cancelled": True,
|
|
479
|
+
"timeout": True,
|
|
480
|
+
}
|
|
481
|
+
)
|
|
482
|
+
return QuestionAnswer(cancelled=True)
|
|
483
|
+
except asyncio.CancelledError:
|
|
484
|
+
self.publish(
|
|
485
|
+
{
|
|
486
|
+
"type": "question_response",
|
|
487
|
+
"requestId": request_id,
|
|
488
|
+
"selected": [],
|
|
489
|
+
"custom": "",
|
|
490
|
+
"cancelled": True,
|
|
491
|
+
}
|
|
492
|
+
)
|
|
493
|
+
raise
|
|
494
|
+
finally:
|
|
495
|
+
self._pending_questions.pop(request_id, None)
|
|
496
|
+
|
|
497
|
+
def answer_question(self, request_id: str, selected: Sequence[str], custom: str) -> JsonValue:
|
|
498
|
+
"""客户端回答一次提问。全空按取消处理,与 REPL 的空行语义一致。"""
|
|
499
|
+
pending = self._pending_questions.get(request_id)
|
|
500
|
+
if pending is None or pending.future.done():
|
|
501
|
+
raise not_found(f"没有挂起的提问: {request_id}")
|
|
502
|
+
answer = (
|
|
503
|
+
QuestionAnswer(selected=tuple(selected), custom=custom)
|
|
504
|
+
if selected or custom
|
|
505
|
+
else QuestionAnswer(cancelled=True)
|
|
506
|
+
)
|
|
507
|
+
pending.future.set_result(answer)
|
|
508
|
+
self.publish(
|
|
509
|
+
{
|
|
510
|
+
"type": "question_response",
|
|
511
|
+
"requestId": request_id,
|
|
512
|
+
"selected": list(selected),
|
|
513
|
+
"custom": custom,
|
|
514
|
+
"cancelled": answer.cancelled,
|
|
515
|
+
}
|
|
516
|
+
)
|
|
517
|
+
return {"requestId": request_id, "cancelled": answer.cancelled}
|
|
518
|
+
|
|
519
|
+
def pending_questions(self) -> list[JsonValue]:
|
|
520
|
+
"""当前挂起的提问。"""
|
|
521
|
+
return [
|
|
522
|
+
{"requestId": request_id, "question": pending.question}
|
|
523
|
+
for request_id, pending in self._pending_questions.items()
|
|
524
|
+
if not pending.future.done()
|
|
525
|
+
]
|
|
526
|
+
|
|
527
|
+
def _cancel_pending_questions(self) -> None:
|
|
528
|
+
for pending in self._pending_questions.values():
|
|
529
|
+
if not pending.future.done():
|
|
530
|
+
pending.future.set_result(QuestionAnswer(cancelled=True))
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""从路由表生成 OpenAPI 3.1 文档。
|
|
2
|
+
|
|
3
|
+
文档不是手写 JSON,也不是另一份路由声明:路径、方法、查询参数、请求体与成功响应
|
|
4
|
+
全部来自 :class:`~braid_coding_agent.server.router.Route` 与请求体 dataclass 的类型
|
|
5
|
+
注解。新增一条路由,文档自动多一条——手写文档最典型的失败是"代码改了,文档没改"。
|
|
6
|
+
|
|
7
|
+
请求体 Schema 由 :func:`braid_coding_agent.server.schema.describe` 生成,与运行时
|
|
8
|
+
校验读同一份注解,因此不会出现"文档说可选、服务端说必填"。
|
|
9
|
+
|
|
10
|
+
## 401 与错误体
|
|
11
|
+
|
|
12
|
+
除 ``/health`` 之外的路径都可能返回 401,错误形状统一是
|
|
13
|
+
``{"error": {"code", "message"}}``。这两条写在文档的 ``components`` 里,
|
|
14
|
+
每条路由用 ``$ref`` 引用,不重复展开。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from .router import Route
|
|
23
|
+
from .schema import describe
|
|
24
|
+
|
|
25
|
+
__all__ = ["document", "error_responses"]
|
|
26
|
+
|
|
27
|
+
_PATH_PARAM = re.compile(r"\{([^}]+)\}")
|
|
28
|
+
|
|
29
|
+
_ERROR_SCHEMA: dict[str, Any] = {
|
|
30
|
+
"type": "object",
|
|
31
|
+
"properties": {
|
|
32
|
+
"error": {
|
|
33
|
+
"type": "object",
|
|
34
|
+
"properties": {
|
|
35
|
+
"code": {"type": "string"},
|
|
36
|
+
"message": {"type": "string"},
|
|
37
|
+
"details": {"type": "object"},
|
|
38
|
+
},
|
|
39
|
+
"required": ["code", "message"],
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"required": ["error"],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def document(routes: list[Route], *, version: str, title: str = "Braid HTTP API") -> dict[str, Any]:
|
|
47
|
+
"""路由表 → OpenAPI 文档。"""
|
|
48
|
+
paths: dict[str, dict[str, Any]] = {}
|
|
49
|
+
for route in routes:
|
|
50
|
+
entry = paths.setdefault(route.path, {})
|
|
51
|
+
entry[route.method.lower()] = _operation(route)
|
|
52
|
+
return {
|
|
53
|
+
"openapi": "3.1.0",
|
|
54
|
+
"info": {
|
|
55
|
+
"title": title,
|
|
56
|
+
"version": version,
|
|
57
|
+
"description": (
|
|
58
|
+
"Braid 的 HTTP 接口。会话、消息、事件流、模型、文件、MCP 与检查点"
|
|
59
|
+
"共用一套 JSON 形状;事件流是 Server-Sent Events。"
|
|
60
|
+
),
|
|
61
|
+
},
|
|
62
|
+
"servers": [{"url": "/"}],
|
|
63
|
+
"paths": paths,
|
|
64
|
+
"components": {
|
|
65
|
+
"schemas": {"Error": _ERROR_SCHEMA},
|
|
66
|
+
"responses": error_responses(),
|
|
67
|
+
"securitySchemes": {"bearer": {"type": "http", "scheme": "bearer"}},
|
|
68
|
+
},
|
|
69
|
+
"security": [{"bearer": []}],
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _operation(route: Route) -> dict[str, Any]:
|
|
74
|
+
"""一条路由 → 一个 operation 对象。"""
|
|
75
|
+
operation: dict[str, Any] = {
|
|
76
|
+
"summary": route.summary,
|
|
77
|
+
"operationId": _operation_id(route),
|
|
78
|
+
"responses": {
|
|
79
|
+
str(route.status): {"description": "成功", **_response_content(route)},
|
|
80
|
+
"400": {"$ref": "#/components/responses/BadRequest"},
|
|
81
|
+
"401": {"$ref": "#/components/responses/Unauthorized"},
|
|
82
|
+
"404": {"$ref": "#/components/responses/NotFound"},
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
if route.tags:
|
|
86
|
+
operation["tags"] = list(route.tags)
|
|
87
|
+
parameters = _parameters(route)
|
|
88
|
+
if parameters:
|
|
89
|
+
operation["parameters"] = parameters
|
|
90
|
+
if route.body is not None:
|
|
91
|
+
operation["requestBody"] = {
|
|
92
|
+
"required": True,
|
|
93
|
+
"content": {"application/json": {"schema": describe(route.body)}},
|
|
94
|
+
}
|
|
95
|
+
return operation
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _response_content(route: Route) -> dict[str, Any]:
|
|
99
|
+
"""成功响应体。SSE 路由声明成 ``text/event-stream``。"""
|
|
100
|
+
if route.sse:
|
|
101
|
+
return {"content": {"text/event-stream": {"schema": {"type": "string"}}}}
|
|
102
|
+
if route.response is None:
|
|
103
|
+
return {"content": {}}
|
|
104
|
+
return {"content": {"application/json": {"schema": route.response}}}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _parameters(route: Route) -> list[Any]:
|
|
108
|
+
"""路径参数 + 查询参数。"""
|
|
109
|
+
parameters: list[Any] = [
|
|
110
|
+
{
|
|
111
|
+
"name": name,
|
|
112
|
+
"in": "path",
|
|
113
|
+
"required": True,
|
|
114
|
+
"schema": {"type": "string"},
|
|
115
|
+
}
|
|
116
|
+
for name in _PATH_PARAM.findall(route.path)
|
|
117
|
+
]
|
|
118
|
+
for param in route.query:
|
|
119
|
+
parameters.append(
|
|
120
|
+
{
|
|
121
|
+
"name": param.name,
|
|
122
|
+
"in": "query",
|
|
123
|
+
"required": param.required,
|
|
124
|
+
"description": param.description,
|
|
125
|
+
"schema": param.schema,
|
|
126
|
+
}
|
|
127
|
+
)
|
|
128
|
+
return parameters
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _operation_id(route: Route) -> str:
|
|
132
|
+
"""``GET /sessions/{id}/messages`` → ``get_sessions_id_messages``。"""
|
|
133
|
+
pieces = [route.method.lower()]
|
|
134
|
+
for part in route.path.strip("/").split("/"):
|
|
135
|
+
if not part:
|
|
136
|
+
continue
|
|
137
|
+
pieces.append(_PATH_PARAM.sub(r"\1", part).replace("-", "_"))
|
|
138
|
+
return "_".join(pieces)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def error_responses() -> dict[str, Any]:
|
|
142
|
+
"""错误响应的共享定义,放进 ``components.responses``。"""
|
|
143
|
+
schema = {"$ref": "#/components/schemas/Error"}
|
|
144
|
+
return {
|
|
145
|
+
"BadRequest": {
|
|
146
|
+
"description": "请求不合法",
|
|
147
|
+
"content": {"application/json": {"schema": schema}},
|
|
148
|
+
},
|
|
149
|
+
"Unauthorized": {
|
|
150
|
+
"description": "缺少或无效的 Bearer Token",
|
|
151
|
+
"content": {"application/json": {"schema": schema}},
|
|
152
|
+
},
|
|
153
|
+
"NotFound": {
|
|
154
|
+
"description": "资源不存在",
|
|
155
|
+
"content": {"application/json": {"schema": schema}},
|
|
156
|
+
},
|
|
157
|
+
}
|