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,386 @@
|
|
|
1
|
+
"""同步 SDK:把 HTTP 接口包成方法调用。
|
|
2
|
+
|
|
3
|
+
```python
|
|
4
|
+
from braid_coding_agent.sdk import BraidClient
|
|
5
|
+
|
|
6
|
+
with BraidClient("http://127.0.0.1:4096", token="...") as client:
|
|
7
|
+
session = client.create_session(name="演示")
|
|
8
|
+
result = client.run(session.id, "读一下 README 并概括")
|
|
9
|
+
print(result.text)
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## 两条使用路径
|
|
13
|
+
|
|
14
|
+
- **细粒度**:``send_message`` 立刻返回 ``started``,进度从 ``events`` 读。适合编辑器
|
|
15
|
+
与服务端事件绑定的场景——UI 要边收边画。
|
|
16
|
+
- **粗粒度**:``run`` 打开事件流、发消息、读到 ``agent_settled``,再返回最后一条助手
|
|
17
|
+
消息。脚本与 CI 用这一条就够。
|
|
18
|
+
|
|
19
|
+
## 超时
|
|
20
|
+
|
|
21
|
+
默认读超时是 ``None``:一次 Agent 回合可能跑几分钟,SSE 连接在两次事件之间也会
|
|
22
|
+
安静很久。连接超时仍是 10 秒——连不上本机服务应该立刻失败。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from collections.abc import Callable, Iterator, Mapping, Sequence
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
import httpx
|
|
31
|
+
|
|
32
|
+
from .errors import BraidApiError
|
|
33
|
+
from .events import Event, last_assistant_text, parse_frames
|
|
34
|
+
from .types import RunResult, Session
|
|
35
|
+
from .wire import clean_params, decode_json, dict_items, require_dict, seg
|
|
36
|
+
|
|
37
|
+
__all__ = ["BraidClient", "EventStream"]
|
|
38
|
+
|
|
39
|
+
#: 默认监听地址。与 ``braid serve`` 的默认值一致。
|
|
40
|
+
DEFAULT_BASE_URL = "http://127.0.0.1:4096"
|
|
41
|
+
|
|
42
|
+
#: 默认超时。读不设上限:长回合与长连接都是正常情况。
|
|
43
|
+
DEFAULT_TIMEOUT = httpx.Timeout(connect=10.0, read=None, write=60.0, pool=10.0)
|
|
44
|
+
|
|
45
|
+
JsonBody = Mapping[str, Any] | None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class EventStream:
|
|
49
|
+
"""一条打开的 SSE 连接。可迭代、可关闭、可当上下文管理器用。"""
|
|
50
|
+
|
|
51
|
+
def __init__(self, response: httpx.Response) -> None:
|
|
52
|
+
self._response = response
|
|
53
|
+
self._lines = response.iter_lines()
|
|
54
|
+
|
|
55
|
+
def __iter__(self) -> Iterator[Event]:
|
|
56
|
+
yield from parse_frames(self._lines)
|
|
57
|
+
|
|
58
|
+
def close(self) -> None:
|
|
59
|
+
self._response.close()
|
|
60
|
+
|
|
61
|
+
def __enter__(self) -> EventStream:
|
|
62
|
+
return self
|
|
63
|
+
|
|
64
|
+
def __exit__(self, *_: object) -> None:
|
|
65
|
+
self.close()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class BraidClient:
|
|
69
|
+
"""同步客户端。
|
|
70
|
+
|
|
71
|
+
:param base_url: 服务地址,例如 ``http://127.0.0.1:4096``。
|
|
72
|
+
:param token: 服务端配置的 Bearer Token;没配令牌时省略。
|
|
73
|
+
:param client: 自带 ``httpx.Client``(代理、自定义 TLS、测试传输)。给了它
|
|
74
|
+
就不由本对象关闭。
|
|
75
|
+
:param transport: 传给内部 ``httpx.Client`` 的传输层,测试用 ``MockTransport``。
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
81
|
+
*,
|
|
82
|
+
token: str | None = None,
|
|
83
|
+
timeout: httpx.Timeout | float | None = None,
|
|
84
|
+
client: httpx.Client | None = None,
|
|
85
|
+
transport: httpx.BaseTransport | None = None,
|
|
86
|
+
) -> None:
|
|
87
|
+
headers = {"Authorization": f"Bearer {token}"} if token else {}
|
|
88
|
+
self._owns_client = client is None
|
|
89
|
+
self._client = client or httpx.Client(
|
|
90
|
+
base_url=base_url.rstrip("/"),
|
|
91
|
+
headers=headers,
|
|
92
|
+
timeout=DEFAULT_TIMEOUT if timeout is None else timeout,
|
|
93
|
+
transport=transport,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# ---------------------------------------------------------------- 生命周期
|
|
97
|
+
|
|
98
|
+
def close(self) -> None:
|
|
99
|
+
if self._owns_client:
|
|
100
|
+
self._client.close()
|
|
101
|
+
|
|
102
|
+
def __enter__(self) -> BraidClient:
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
def __exit__(self, *_: object) -> None:
|
|
106
|
+
self.close()
|
|
107
|
+
|
|
108
|
+
# ------------------------------------------------------------------ 元信息
|
|
109
|
+
|
|
110
|
+
def health(self) -> dict[str, Any]:
|
|
111
|
+
"""存活检查。不需要令牌。"""
|
|
112
|
+
return self._json("GET", "/health")
|
|
113
|
+
|
|
114
|
+
def openapi(self) -> dict[str, Any]:
|
|
115
|
+
"""服务端的 OpenAPI 文档。"""
|
|
116
|
+
return self._json("GET", "/openapi.json")
|
|
117
|
+
|
|
118
|
+
def models(self) -> list[dict[str, Any]]:
|
|
119
|
+
"""模型目录。"""
|
|
120
|
+
return dict_items(self._json("GET", "/models").get("models"))
|
|
121
|
+
|
|
122
|
+
# -------------------------------------------------------------------- 会话
|
|
123
|
+
|
|
124
|
+
def create_session(self, name: str | None = None, *, parent: str | None = None) -> Session:
|
|
125
|
+
payload = self._json(
|
|
126
|
+
"POST",
|
|
127
|
+
"/sessions",
|
|
128
|
+
body={"name": name, "parentSession": parent},
|
|
129
|
+
expected=(201,),
|
|
130
|
+
)
|
|
131
|
+
return Session.from_wire(require_dict(payload.get("session")))
|
|
132
|
+
|
|
133
|
+
def list_sessions(self, *, limit: int = 50) -> list[Session]:
|
|
134
|
+
payload = self._json("GET", "/sessions", params={"limit": limit})
|
|
135
|
+
return [Session.from_wire(item) for item in dict_items(payload.get("sessions"))]
|
|
136
|
+
|
|
137
|
+
def get_session(self, session_id: str) -> Session:
|
|
138
|
+
"""读取一个会话。这条调用会把磁盘上的会话打开成活的会话。"""
|
|
139
|
+
payload = self._json("GET", f"/sessions/{seg(session_id)}")
|
|
140
|
+
return Session.from_wire(require_dict(payload.get("session")))
|
|
141
|
+
|
|
142
|
+
def delete_session(self, session_id: str) -> None:
|
|
143
|
+
self._request("DELETE", f"/sessions/{seg(session_id)}", expected=(204,))
|
|
144
|
+
|
|
145
|
+
def fork_session(self, session_id: str, entry_id: str | None = None) -> Session:
|
|
146
|
+
payload = self._json(
|
|
147
|
+
"POST",
|
|
148
|
+
f"/sessions/{seg(session_id)}/fork",
|
|
149
|
+
body={"entryId": entry_id},
|
|
150
|
+
expected=(201,),
|
|
151
|
+
)
|
|
152
|
+
return Session.from_wire(require_dict(payload.get("session")))
|
|
153
|
+
|
|
154
|
+
def state(self, session_id: str) -> dict[str, Any]:
|
|
155
|
+
"""会话状态:模型、上下文、费用、计划、检查点。"""
|
|
156
|
+
return self._json("GET", f"/sessions/{seg(session_id)}/state")
|
|
157
|
+
|
|
158
|
+
def plan(self, session_id: str, action: str, *, goal: str | None = None) -> dict[str, Any]:
|
|
159
|
+
"""进入、批准或退出规划模式,返回 ``planMode`` 状态。
|
|
160
|
+
|
|
161
|
+
``action`` 是 ``enter`` / ``approve`` / ``leave``。批准是客户端的一次显式
|
|
162
|
+
动作:计划正文本就在 ``state()["planMode"]["plan"]`` 里。
|
|
163
|
+
"""
|
|
164
|
+
body: dict[str, Any] = {"action": action}
|
|
165
|
+
if goal is not None:
|
|
166
|
+
body["goal"] = goal
|
|
167
|
+
payload = self._json("POST", f"/sessions/{seg(session_id)}/plan", body=body)
|
|
168
|
+
return require_dict(payload.get("planMode"))
|
|
169
|
+
|
|
170
|
+
# -------------------------------------------------------------------- 消息
|
|
171
|
+
|
|
172
|
+
def send_message(
|
|
173
|
+
self,
|
|
174
|
+
session_id: str,
|
|
175
|
+
text: str,
|
|
176
|
+
*,
|
|
177
|
+
images: Sequence[Mapping[str, str]] | None = None,
|
|
178
|
+
behavior: str = "prompt",
|
|
179
|
+
wait: bool = False,
|
|
180
|
+
) -> dict[str, Any]:
|
|
181
|
+
"""发送一条消息。``wait=True`` 时服务端等到回合结束才返回。"""
|
|
182
|
+
body: dict[str, Any] = {"text": text, "behavior": behavior, "wait": wait}
|
|
183
|
+
if images is not None:
|
|
184
|
+
body["images"] = list(images)
|
|
185
|
+
return self._json("POST", f"/sessions/{seg(session_id)}/messages", body=body)
|
|
186
|
+
|
|
187
|
+
def messages(self, session_id: str) -> list[dict[str, Any]]:
|
|
188
|
+
payload = self._json("GET", f"/sessions/{seg(session_id)}/messages")
|
|
189
|
+
return dict_items(payload.get("messages"))
|
|
190
|
+
|
|
191
|
+
def abort(self, session_id: str) -> None:
|
|
192
|
+
self._json("POST", f"/sessions/{seg(session_id)}/abort")
|
|
193
|
+
|
|
194
|
+
# -------------------------------------------------------------------- 配置
|
|
195
|
+
|
|
196
|
+
def set_model(self, session_id: str, provider: str, model_id: str) -> dict[str, Any]:
|
|
197
|
+
return self._json(
|
|
198
|
+
"PUT",
|
|
199
|
+
f"/sessions/{seg(session_id)}/model",
|
|
200
|
+
body={"provider": provider, "modelId": model_id},
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
def set_thinking(self, session_id: str, level: str) -> dict[str, Any]:
|
|
204
|
+
return self._json("PUT", f"/sessions/{seg(session_id)}/thinking", body={"level": level})
|
|
205
|
+
|
|
206
|
+
def compact(self, session_id: str, instructions: str | None = None) -> dict[str, Any]:
|
|
207
|
+
return self._json(
|
|
208
|
+
"POST",
|
|
209
|
+
f"/sessions/{seg(session_id)}/compact",
|
|
210
|
+
body={"instructions": instructions},
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
def undo(self, session_id: str) -> dict[str, Any]:
|
|
214
|
+
return self._json("POST", f"/sessions/{seg(session_id)}/undo")
|
|
215
|
+
|
|
216
|
+
def redo(self, session_id: str) -> dict[str, Any]:
|
|
217
|
+
return self._json("POST", f"/sessions/{seg(session_id)}/redo")
|
|
218
|
+
|
|
219
|
+
def diff(self, session_id: str) -> dict[str, Any]:
|
|
220
|
+
return self._json("GET", f"/sessions/{seg(session_id)}/diff")
|
|
221
|
+
|
|
222
|
+
# ---------------------------------------------------------------- 批准与提问
|
|
223
|
+
|
|
224
|
+
def pending(self, session_id: str) -> dict[str, Any]:
|
|
225
|
+
return self._json("GET", f"/sessions/{seg(session_id)}/pending")
|
|
226
|
+
|
|
227
|
+
def answer_permission(self, session_id: str, request_id: str, scope: str) -> dict[str, Any]:
|
|
228
|
+
return self._json(
|
|
229
|
+
"POST",
|
|
230
|
+
f"/sessions/{seg(session_id)}/permissions/{seg(request_id)}",
|
|
231
|
+
body={"scope": scope},
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
def answer_question(
|
|
235
|
+
self,
|
|
236
|
+
session_id: str,
|
|
237
|
+
request_id: str,
|
|
238
|
+
*,
|
|
239
|
+
selected: Sequence[str] | None = None,
|
|
240
|
+
custom: str | None = None,
|
|
241
|
+
) -> dict[str, Any]:
|
|
242
|
+
return self._json(
|
|
243
|
+
"POST",
|
|
244
|
+
f"/sessions/{seg(session_id)}/questions/{seg(request_id)}",
|
|
245
|
+
body={"selected": list(selected) if selected is not None else None, "custom": custom},
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
# -------------------------------------------------------------------- 文件
|
|
249
|
+
|
|
250
|
+
def read_file(
|
|
251
|
+
self, path: str, *, offset: int | None = None, limit: int | None = None
|
|
252
|
+
) -> dict[str, Any]:
|
|
253
|
+
"""读工作区内的文本文件。路径必须落在工作区里。"""
|
|
254
|
+
return self._json("GET", "/files", params={"path": path, "offset": offset, "limit": limit})
|
|
255
|
+
|
|
256
|
+
def search(
|
|
257
|
+
self,
|
|
258
|
+
pattern: str,
|
|
259
|
+
*,
|
|
260
|
+
path: str | None = None,
|
|
261
|
+
glob: str | None = None,
|
|
262
|
+
ignore_case: bool = False,
|
|
263
|
+
literal: bool = False,
|
|
264
|
+
context: int = 0,
|
|
265
|
+
limit: int = 100,
|
|
266
|
+
) -> dict[str, Any]:
|
|
267
|
+
"""内容搜索。与模型的 ``grep`` 工具同一套匹配规则。"""
|
|
268
|
+
return self._json(
|
|
269
|
+
"GET",
|
|
270
|
+
"/files/search",
|
|
271
|
+
params={
|
|
272
|
+
"pattern": pattern,
|
|
273
|
+
"path": path,
|
|
274
|
+
"glob": glob,
|
|
275
|
+
"ignoreCase": ignore_case,
|
|
276
|
+
"literal": literal,
|
|
277
|
+
"context": context,
|
|
278
|
+
"limit": limit,
|
|
279
|
+
},
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
def find(self, pattern: str, *, path: str | None = None, limit: int = 1000) -> dict[str, Any]:
|
|
283
|
+
"""按 glob 找文件。"""
|
|
284
|
+
return self._json(
|
|
285
|
+
"GET", "/files/find", params={"pattern": pattern, "path": path, "limit": limit}
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
# --------------------------------------------------------------------- MCP
|
|
289
|
+
|
|
290
|
+
def mcp(self) -> dict[str, Any]:
|
|
291
|
+
return self._json("GET", "/mcp")
|
|
292
|
+
|
|
293
|
+
def enable_mcp(self, name: str) -> dict[str, Any]:
|
|
294
|
+
return self._json("POST", f"/mcp/{seg(name)}/enable")
|
|
295
|
+
|
|
296
|
+
def disable_mcp(self, name: str) -> dict[str, Any]:
|
|
297
|
+
return self._json("POST", f"/mcp/{seg(name)}/disable")
|
|
298
|
+
|
|
299
|
+
# -------------------------------------------------------------------- 事件
|
|
300
|
+
|
|
301
|
+
def events(self, session_id: str, *, since: int | None = None) -> EventStream:
|
|
302
|
+
"""打开会话事件流。返回的对象要关闭(或用 ``with``)。
|
|
303
|
+
|
|
304
|
+
打开成功意味着服务端已经完成订阅:在它之后发送的消息不会漏掉事件。
|
|
305
|
+
"""
|
|
306
|
+
request = self._client.build_request(
|
|
307
|
+
"GET",
|
|
308
|
+
f"/sessions/{seg(session_id)}/events",
|
|
309
|
+
params=None if since is None else {"since": since},
|
|
310
|
+
)
|
|
311
|
+
response = self._client.send(request, stream=True)
|
|
312
|
+
if response.status_code != 200:
|
|
313
|
+
response.read()
|
|
314
|
+
payload = decode_json(response)
|
|
315
|
+
response.close()
|
|
316
|
+
raise BraidApiError.from_payload(response.status_code, payload)
|
|
317
|
+
return EventStream(response)
|
|
318
|
+
|
|
319
|
+
def run(
|
|
320
|
+
self,
|
|
321
|
+
session_id: str,
|
|
322
|
+
text: str,
|
|
323
|
+
*,
|
|
324
|
+
images: Sequence[Mapping[str, str]] | None = None,
|
|
325
|
+
on_event: Callable[[Event], None] | None = None,
|
|
326
|
+
) -> RunResult:
|
|
327
|
+
"""发一条消息并读到 ``agent_settled``,返回最终结果。
|
|
328
|
+
|
|
329
|
+
先开事件流再发消息:反过来的话,从发送到订阅之间产生的事件会丢。
|
|
330
|
+
"""
|
|
331
|
+
settled = False
|
|
332
|
+
aborted = False
|
|
333
|
+
stream = self.events(session_id)
|
|
334
|
+
try:
|
|
335
|
+
frames = iter(stream)
|
|
336
|
+
next(frames, None) # ready
|
|
337
|
+
self.send_message(session_id, text, images=images)
|
|
338
|
+
for event in frames:
|
|
339
|
+
if on_event is not None:
|
|
340
|
+
on_event(event)
|
|
341
|
+
if event.type == "agent_settled":
|
|
342
|
+
settled = True
|
|
343
|
+
aborted = bool(event.data.get("aborted"))
|
|
344
|
+
break
|
|
345
|
+
finally:
|
|
346
|
+
stream.close()
|
|
347
|
+
messages = self.messages(session_id)
|
|
348
|
+
return RunResult(
|
|
349
|
+
text=last_assistant_text(messages),
|
|
350
|
+
messages=messages,
|
|
351
|
+
aborted=aborted,
|
|
352
|
+
settled=settled,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
# -------------------------------------------------------------------- 内部
|
|
356
|
+
|
|
357
|
+
def _request(
|
|
358
|
+
self,
|
|
359
|
+
method: str,
|
|
360
|
+
path: str,
|
|
361
|
+
*,
|
|
362
|
+
params: Mapping[str, Any] | None = None,
|
|
363
|
+
body: JsonBody = None,
|
|
364
|
+
expected: tuple[int, ...] = (200,),
|
|
365
|
+
) -> httpx.Response:
|
|
366
|
+
response = self._client.request(
|
|
367
|
+
method,
|
|
368
|
+
path,
|
|
369
|
+
params=clean_params(params),
|
|
370
|
+
json=dict(body) if body is not None else None,
|
|
371
|
+
)
|
|
372
|
+
if response.status_code not in expected:
|
|
373
|
+
raise BraidApiError.from_payload(response.status_code, decode_json(response))
|
|
374
|
+
return response
|
|
375
|
+
|
|
376
|
+
def _json(
|
|
377
|
+
self,
|
|
378
|
+
method: str,
|
|
379
|
+
path: str,
|
|
380
|
+
*,
|
|
381
|
+
params: Mapping[str, Any] | None = None,
|
|
382
|
+
body: JsonBody = None,
|
|
383
|
+
expected: tuple[int, ...] = (200,),
|
|
384
|
+
) -> dict[str, Any]:
|
|
385
|
+
response = self._request(method, path, params=params, body=body, expected=expected)
|
|
386
|
+
return require_dict(decode_json(response))
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""SDK 的异常类型。
|
|
2
|
+
|
|
3
|
+
服务端把所有失败折成 ``{"error": {"code", "message", "details"}}``。SDK 只做一件事:
|
|
4
|
+
把它抬成一个带状态码与错误码的异常,调用方按 ``code`` 分支,不用去解析字符串。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from braid_ai.types import JsonValue
|
|
12
|
+
|
|
13
|
+
__all__ = ["BraidApiError"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class BraidApiError(Exception):
|
|
17
|
+
"""一次 HTTP 调用失败。
|
|
18
|
+
|
|
19
|
+
:param status: HTTP 状态码。连接层面的失败(拒绝连接、超时)由 ``httpx`` 自己抛,
|
|
20
|
+
不属于这个异常。
|
|
21
|
+
:param code: 服务端的错误码,例如 ``not_found`` / ``conflict`` / ``unauthorized``。
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
status: int,
|
|
27
|
+
code: str,
|
|
28
|
+
message: str,
|
|
29
|
+
details: dict[str, Any] | None = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
super().__init__(f"{status} {code}: {message}")
|
|
32
|
+
self.status = status
|
|
33
|
+
self.code = code
|
|
34
|
+
self.message = message
|
|
35
|
+
self.details = details
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def from_payload(cls, status: int, payload: JsonValue) -> BraidApiError:
|
|
39
|
+
"""从服务端的错误体构造。形状不对时按 ``internal`` 处理,保留原始文本。"""
|
|
40
|
+
if isinstance(payload, dict):
|
|
41
|
+
error = payload.get("error")
|
|
42
|
+
if isinstance(error, dict):
|
|
43
|
+
code = error.get("code")
|
|
44
|
+
message = error.get("message")
|
|
45
|
+
details = error.get("details")
|
|
46
|
+
return cls(
|
|
47
|
+
status,
|
|
48
|
+
code if isinstance(code, str) else "internal",
|
|
49
|
+
message if isinstance(message, str) else "请求失败",
|
|
50
|
+
details if isinstance(details, dict) else None,
|
|
51
|
+
)
|
|
52
|
+
return cls(status, "internal", f"服务端返回了非错误格式的响应: {payload!r}")
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""SDK 的事件模型与 SSE 解析。
|
|
2
|
+
|
|
3
|
+
服务端的一帧是标准的 ``text/event-stream``:
|
|
4
|
+
|
|
5
|
+
```text
|
|
6
|
+
id: 12
|
|
7
|
+
event: message_end
|
|
8
|
+
data: {"seq": 12, "type": "message_end", "message": {...}}
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
``id`` 与 ``data.seq`` 是同一个序号。解析器两处都认:``id`` 用来在重连时填
|
|
12
|
+
``Last-Event-ID``,``data.seq`` 是客户端排序与去重的依据。
|
|
13
|
+
|
|
14
|
+
## 为什么 ``Event.data`` 是 dict 而不是一堆 dataclass
|
|
15
|
+
|
|
16
|
+
会话事件有二十多种,每一种都建一个类,SDK 就变成服务端事件结构的第二份定义:
|
|
17
|
+
服务端加一个字段,SDK 要跟着发版。事件类型与字段是服务端的契约,SDK 负责搬运。
|
|
18
|
+
需要类型安全的地方(会话、错误)才有 dataclass。
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
from collections.abc import Iterable, Iterator
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from typing import Any, cast
|
|
27
|
+
|
|
28
|
+
__all__ = ["Event", "FrameParser", "last_assistant_text", "parse_frames", "text_of"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(slots=True, frozen=True)
|
|
32
|
+
class Event:
|
|
33
|
+
"""一条会话事件。
|
|
34
|
+
|
|
35
|
+
:param type: ``agent_start`` / ``message_update`` / ``tool_execution_end`` 等。
|
|
36
|
+
:param data: 事件体。``seq`` 一定在里面(服务端保证)。
|
|
37
|
+
:param id: SSE 帧的 ``id``;与服务端分配的序号相同。
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
type: str
|
|
41
|
+
data: dict[str, Any] = field(default_factory=dict[str, Any])
|
|
42
|
+
id: str | None = None
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def seq(self) -> int | None:
|
|
46
|
+
"""事件序号。缺字段返回 ``None``(正常服务端不会缺)。"""
|
|
47
|
+
value = self.data.get("seq")
|
|
48
|
+
if isinstance(value, int):
|
|
49
|
+
return value
|
|
50
|
+
if self.id is not None and self.id.isdigit():
|
|
51
|
+
return int(self.id)
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class FrameParser:
|
|
56
|
+
"""增量帧解析器:一次喂一行,遇到空行产出一帧。
|
|
57
|
+
|
|
58
|
+
同步与异步客户端共用它。按行逐个解析的写法(每行单独 ``parse_frames([line])``)
|
|
59
|
+
会把多行 ``data`` 与空行分隔全部丢掉,只在小载荷下看起来能用。
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
__slots__ = ("_data", "_id", "_started", "_type")
|
|
63
|
+
|
|
64
|
+
def __init__(self) -> None:
|
|
65
|
+
self._type = "message"
|
|
66
|
+
self._id: str | None = None
|
|
67
|
+
self._data: list[str] = []
|
|
68
|
+
self._started = False
|
|
69
|
+
|
|
70
|
+
def feed(self, raw: str) -> Event | None:
|
|
71
|
+
"""喂一行(不含换行)。这一行结束了一帧就返回它。"""
|
|
72
|
+
line = raw.rstrip("\r")
|
|
73
|
+
if line == "":
|
|
74
|
+
return self.flush()
|
|
75
|
+
if line.startswith(":"):
|
|
76
|
+
return None
|
|
77
|
+
field_name, _, value = line.partition(":")
|
|
78
|
+
if value.startswith(" "):
|
|
79
|
+
value = value[1:]
|
|
80
|
+
if field_name == "event":
|
|
81
|
+
self._type = value
|
|
82
|
+
self._started = True
|
|
83
|
+
elif field_name == "id":
|
|
84
|
+
self._id = value
|
|
85
|
+
self._started = True
|
|
86
|
+
elif field_name == "data":
|
|
87
|
+
self._data.append(value)
|
|
88
|
+
self._started = True
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
def flush(self) -> Event | None:
|
|
92
|
+
"""把缓冲里的内容收成一帧。没有内容时返回 ``None``。"""
|
|
93
|
+
if not self._started:
|
|
94
|
+
return None
|
|
95
|
+
event = Event(
|
|
96
|
+
type=self._type,
|
|
97
|
+
data=_decode("\n".join(self._data)),
|
|
98
|
+
id=self._id,
|
|
99
|
+
)
|
|
100
|
+
self._type = "message"
|
|
101
|
+
self._id = None
|
|
102
|
+
self._data = []
|
|
103
|
+
self._started = False
|
|
104
|
+
return event
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def parse_frames(lines: Iterable[str]) -> Iterator[Event]:
|
|
108
|
+
"""把 SSE 行流切成事件。
|
|
109
|
+
|
|
110
|
+
只实现本服务会用到的三个字段(``id`` / ``event`` / ``data``);``retry`` 与
|
|
111
|
+
注释行忽略。多行 ``data`` 按规范用 ``\\n`` 拼起来。
|
|
112
|
+
|
|
113
|
+
流结束时没有空行收尾的最后一帧照样交付:服务端关闭连接时可能来不及补空行。
|
|
114
|
+
"""
|
|
115
|
+
parser = FrameParser()
|
|
116
|
+
for raw in lines:
|
|
117
|
+
event = parser.feed(raw)
|
|
118
|
+
if event is not None:
|
|
119
|
+
yield event
|
|
120
|
+
tail = parser.flush()
|
|
121
|
+
if tail is not None:
|
|
122
|
+
yield tail
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _decode(payload: str) -> dict[str, Any]:
|
|
126
|
+
"""一帧的 ``data`` → dict。非对象载荷包成 ``{"value": ...}``。"""
|
|
127
|
+
if not payload:
|
|
128
|
+
return {}
|
|
129
|
+
try:
|
|
130
|
+
parsed: object = json.loads(payload)
|
|
131
|
+
except json.JSONDecodeError:
|
|
132
|
+
return {"value": payload}
|
|
133
|
+
if isinstance(parsed, dict):
|
|
134
|
+
return cast("dict[str, Any]", parsed)
|
|
135
|
+
return {"value": parsed}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def text_of(message: dict[str, Any]) -> str:
|
|
139
|
+
"""一条消息 wire 里的全部文本块。``message_end.message`` 与转录同形。"""
|
|
140
|
+
content = message.get("content")
|
|
141
|
+
if not isinstance(content, list):
|
|
142
|
+
return ""
|
|
143
|
+
parts: list[str] = []
|
|
144
|
+
for block in cast("list[object]", content):
|
|
145
|
+
if not isinstance(block, dict):
|
|
146
|
+
continue
|
|
147
|
+
typed = cast("dict[str, object]", block)
|
|
148
|
+
if typed.get("type") != "text":
|
|
149
|
+
continue
|
|
150
|
+
text = typed.get("text")
|
|
151
|
+
if isinstance(text, str):
|
|
152
|
+
parts.append(text)
|
|
153
|
+
return "".join(parts)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def last_assistant_text(messages: Iterable[dict[str, Any]]) -> str:
|
|
157
|
+
"""最后一条助手消息的文本。没有助手消息时是空串。"""
|
|
158
|
+
found = ""
|
|
159
|
+
for message in messages:
|
|
160
|
+
if message.get("role") == "assistant":
|
|
161
|
+
found = text_of(message)
|
|
162
|
+
return found
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""SDK 的数据类型:会话摘要与一次运行的结果。
|
|
2
|
+
|
|
3
|
+
只有两类东西值得建 dataclass:调用方会反复读的字段(会话的 id、标题、消息数)与
|
|
4
|
+
会被当成返回值传播的结构(运行结果)。事件体保持 dict,理由见 :mod:`.events`。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
__all__ = ["RunResult", "Session"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(slots=True, frozen=True)
|
|
16
|
+
class Session:
|
|
17
|
+
"""一个会话的摘要。字段与 ``GET /sessions`` 的返回一致。"""
|
|
18
|
+
|
|
19
|
+
id: str
|
|
20
|
+
name: str | None
|
|
21
|
+
cwd: str
|
|
22
|
+
created_at: str
|
|
23
|
+
updated_at: str
|
|
24
|
+
message_count: int
|
|
25
|
+
parent_session: str | None
|
|
26
|
+
live: bool
|
|
27
|
+
path: str | None
|
|
28
|
+
#: 原始 wire,包含服务端将来新增的字段。
|
|
29
|
+
raw: dict[str, Any] = field(default_factory=dict[str, Any])
|
|
30
|
+
|
|
31
|
+
@classmethod
|
|
32
|
+
def from_wire(cls, payload: dict[str, Any]) -> Session:
|
|
33
|
+
"""wire → 对象。缺字段时用空值,不因为服务端多一个字段就失败。"""
|
|
34
|
+
return cls(
|
|
35
|
+
id=str(payload.get("id", "")),
|
|
36
|
+
name=payload.get("name") if isinstance(payload.get("name"), str) else None,
|
|
37
|
+
cwd=str(payload.get("cwd", "")),
|
|
38
|
+
created_at=str(payload.get("createdAt", "")),
|
|
39
|
+
updated_at=str(payload.get("updatedAt", "")),
|
|
40
|
+
message_count=int(payload.get("messageCount", 0) or 0),
|
|
41
|
+
parent_session=(
|
|
42
|
+
payload.get("parentSession")
|
|
43
|
+
if isinstance(payload.get("parentSession"), str)
|
|
44
|
+
else None
|
|
45
|
+
),
|
|
46
|
+
live=bool(payload.get("live", False)),
|
|
47
|
+
path=payload.get("path") if isinstance(payload.get("path"), str) else None,
|
|
48
|
+
raw=payload,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(slots=True, frozen=True)
|
|
53
|
+
class RunResult:
|
|
54
|
+
"""``run()`` 的结果:最后一条助手消息与整段转录。"""
|
|
55
|
+
|
|
56
|
+
#: 最后一条助手消息里的文本。没有助手消息时是空串。
|
|
57
|
+
text: str
|
|
58
|
+
#: 运行结束后的完整转录(wire 形状)。
|
|
59
|
+
messages: list[dict[str, Any]]
|
|
60
|
+
#: 服务端在 ``agent_settled`` 里报告的中止标记。
|
|
61
|
+
aborted: bool = False
|
|
62
|
+
#: 是否真的读到了 ``agent_settled``。连接提前断掉时是 ``False``。
|
|
63
|
+
settled: bool = False
|