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,90 @@
|
|
|
1
|
+
"""按文件路径串行化修改操作。
|
|
2
|
+
|
|
3
|
+
存在的理由只有一条:**读—改—写**不是
|
|
4
|
+
原子操作。两个 ``edit`` 同时作用在同一个文件上时,后写的那个会基于"自己读到的旧内容"
|
|
5
|
+
覆盖前一个的结果,前一个修改无声消失——而模型与用户都以为两次都成功了。
|
|
6
|
+
|
|
7
|
+
## 三处设计选择
|
|
8
|
+
|
|
9
|
+
1. **键是 ``realpath``**。``a/../b``、``./b`` 与指向 ``b`` 的符号链接必须命中同一把锁,
|
|
10
|
+
否则绕过同步只需换一种写法。文件还不存在时(新建)退回 ``abspath``:``realpath``
|
|
11
|
+
对不存在的路径仍然会规范化到父目录的真实路径,因此两个"新建同一路径"的调用
|
|
12
|
+
依然同键。
|
|
13
|
+
2. **不同路径永不互相阻塞**。锁表按路径分片,``grep`` 之类的读操作完全不进这张表。
|
|
14
|
+
3. **锁在没人用时被移除**。否则一次遍历几十万个文件的会话会把锁表留成内存泄漏;
|
|
15
|
+
计数在 ``finally`` 里减,保证异常路径也会释放。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import os
|
|
22
|
+
from collections.abc import Awaitable, Callable
|
|
23
|
+
from typing import Final
|
|
24
|
+
|
|
25
|
+
type _Operation[T] = Callable[[], Awaitable[T]]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _Entry:
|
|
29
|
+
"""一条路径上的锁与使用者计数。计数只在事件循环线程里读写。"""
|
|
30
|
+
|
|
31
|
+
__slots__ = ("lock", "users")
|
|
32
|
+
|
|
33
|
+
def __init__(self) -> None:
|
|
34
|
+
self.lock = asyncio.Lock()
|
|
35
|
+
self.users = 0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class FileMutationQueue:
|
|
39
|
+
"""按绝对路径互斥。同一个实例必须在同一事件循环里使用(``asyncio.Lock`` 的要求)。"""
|
|
40
|
+
|
|
41
|
+
__slots__ = ("_entries", "_guard")
|
|
42
|
+
|
|
43
|
+
def __init__(self) -> None:
|
|
44
|
+
self._entries: dict[str, _Entry] = {}
|
|
45
|
+
self._guard = asyncio.Lock()
|
|
46
|
+
|
|
47
|
+
async def run[T](self, file_path: str, operation: _Operation[T]) -> T:
|
|
48
|
+
"""在 ``file_path`` 的锁内执行 ``operation``,返回它的结果。"""
|
|
49
|
+
key = mutation_key(file_path)
|
|
50
|
+
async with self._guard:
|
|
51
|
+
entry = self._entries.get(key)
|
|
52
|
+
if entry is None:
|
|
53
|
+
entry = _Entry()
|
|
54
|
+
self._entries[key] = entry
|
|
55
|
+
entry.users += 1
|
|
56
|
+
try:
|
|
57
|
+
async with entry.lock:
|
|
58
|
+
return await operation()
|
|
59
|
+
finally:
|
|
60
|
+
async with self._guard:
|
|
61
|
+
entry.users -= 1
|
|
62
|
+
if entry.users == 0 and self._entries.get(key) is entry:
|
|
63
|
+
del self._entries[key]
|
|
64
|
+
|
|
65
|
+
def locked_paths(self) -> int:
|
|
66
|
+
"""当前登记的路径数。测试用它确认锁表不会无限增长。"""
|
|
67
|
+
return len(self._entries)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def mutation_key(file_path: str) -> str:
|
|
71
|
+
"""锁键:真实路径(解析符号链接);解析失败时退回绝对路径。"""
|
|
72
|
+
absolute = os.path.abspath(file_path)
|
|
73
|
+
return os.path.realpath(absolute)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
#: 进程级默认队列。工具在构造时默认用它,测试可以传入自己的实例以获得隔离。
|
|
77
|
+
DEFAULT_MUTATION_QUEUE: Final[FileMutationQueue] = FileMutationQueue()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def with_file_mutation_queue[T](file_path: str, operation: _Operation[T]) -> T:
|
|
81
|
+
"""在默认队列上执行一次修改操作。"""
|
|
82
|
+
return await DEFAULT_MUTATION_QUEUE.run(file_path, operation)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
__all__ = [
|
|
86
|
+
"DEFAULT_MUTATION_QUEUE",
|
|
87
|
+
"FileMutationQueue",
|
|
88
|
+
"mutation_key",
|
|
89
|
+
"with_file_mutation_queue",
|
|
90
|
+
]
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""工具依赖的 I/O 协议:文件系统原语与命令执行。
|
|
2
|
+
|
|
3
|
+
按工具各自定一个 I/O 接口(``ReadOperations``、``WriteOperations``、
|
|
4
|
+
``EditOperations``、``BashOperations``、``GrepOperations``、``FindOperations``、
|
|
5
|
+
``LsOperations``)代价不小:它们其实是同一个对象的七个**部分视图**——
|
|
6
|
+
``read`` 只需要"读字节 + 检查可读",``ls`` 只需要"列目录 + 判断是不是目录",
|
|
7
|
+
接一个远端实现(SSH、容器)要填七个接口,其中五个方法重复。
|
|
8
|
+
|
|
9
|
+
这里合成两个协议:
|
|
10
|
+
|
|
11
|
+
- :class:`FileOperations`:本机文件系统的读写原语,七个文件工具共用;
|
|
12
|
+
- :class:`ShellOperations`:执行一条命令并流式交出输出。
|
|
13
|
+
|
|
14
|
+
**为什么工具不直接 ``open()``**:工具的行为要能在临时目录、内存 FS、远端主机之间
|
|
15
|
+
一致地测试与替换。工具自己 ``open`` 的那一刻,"换一个环境"就必须改
|
|
16
|
+
工具源码;依赖协议则只换一个对象。全部测试正是这么做的——一部分用真实临时
|
|
17
|
+
目录,一部分用内存实现验证"工具只用了协议里的方法"。
|
|
18
|
+
|
|
19
|
+
**为什么 ``check_access`` 不叫 ``access``**:``access`` 是 POSIX 概念(``os.access``),
|
|
20
|
+
而它正是本方法在本地实现里调用的东西;同名会让"协议方法"和"系统调用"在阅读时混淆。
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import asyncio
|
|
26
|
+
import os
|
|
27
|
+
import signal as signal_module
|
|
28
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
29
|
+
from typing import Final, Protocol
|
|
30
|
+
|
|
31
|
+
from braid_ai.cancel import CancelToken
|
|
32
|
+
from braid_coding_agent.cancellation import OperationAborted, ensure_not_cancelled
|
|
33
|
+
|
|
34
|
+
#: 等待子进程退出时的轮询间隔(秒)。
|
|
35
|
+
#:
|
|
36
|
+
#: 为什么是轮询:``CancelToken`` 没有监听器(见 :mod:`braid_ai.cancel`),取消是协作式的。
|
|
37
|
+
#: 20 次/秒的空转成本可以忽略,换来的是没有任何"回调在错误的线程里被调用"的可能。
|
|
38
|
+
_POLL_INTERVAL: Final[float] = 0.05
|
|
39
|
+
|
|
40
|
+
#: 每次从子进程读出的字节数。64KB 是管道缓冲的常见大小,再大也不会更快。
|
|
41
|
+
_READ_CHUNK: Final[int] = 64 * 1024
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class FileOperations(Protocol):
|
|
45
|
+
"""文件系统原语。所有方法都是 async:远端实现天然是异步的,本地实现只是在
|
|
46
|
+
线程池里跑阻塞调用,两者对调用方同形。"""
|
|
47
|
+
|
|
48
|
+
async def exists(self, path: str) -> bool:
|
|
49
|
+
"""路径是否存在(跟随符号链接)。"""
|
|
50
|
+
...
|
|
51
|
+
|
|
52
|
+
async def is_dir(self, path: str) -> bool:
|
|
53
|
+
"""是否是目录(跟随符号链接)。"""
|
|
54
|
+
...
|
|
55
|
+
|
|
56
|
+
async def is_symlink(self, path: str) -> bool:
|
|
57
|
+
"""是否是符号链接。遍历时用它避免跟进目录链接造成的环。"""
|
|
58
|
+
...
|
|
59
|
+
|
|
60
|
+
async def read_bytes(self, path: str) -> bytes:
|
|
61
|
+
"""读取整个文件。``FileNotFoundError`` / ``IsADirectoryError`` 照实抛。"""
|
|
62
|
+
...
|
|
63
|
+
|
|
64
|
+
async def write_text(self, path: str, content: str) -> None:
|
|
65
|
+
"""以 UTF-8 写入整个文件(覆盖)。父目录必须已存在。"""
|
|
66
|
+
...
|
|
67
|
+
|
|
68
|
+
async def write_bytes(self, path: str, data: bytes) -> None:
|
|
69
|
+
"""按调用方给定的字节覆盖整个文件,不做编码与换行转换。"""
|
|
70
|
+
...
|
|
71
|
+
|
|
72
|
+
async def mkdir(self, path: str) -> None:
|
|
73
|
+
"""递归创建目录;已存在视为成功。"""
|
|
74
|
+
...
|
|
75
|
+
|
|
76
|
+
async def readdir(self, path: str) -> list[str]:
|
|
77
|
+
"""列出一级子项名字(不含 ``.``/``..``),顺序不保证。"""
|
|
78
|
+
...
|
|
79
|
+
|
|
80
|
+
async def check_access(self, path: str, *, write: bool = False) -> None:
|
|
81
|
+
"""检查可读(或可读写)。不可访问时抛 ``OSError``,消息带 errno 名称。"""
|
|
82
|
+
...
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class LocalFileOperations:
|
|
86
|
+
"""本机实现。阻塞调用放线程池,避免一次大文件读把事件循环按停。"""
|
|
87
|
+
|
|
88
|
+
__slots__ = ()
|
|
89
|
+
|
|
90
|
+
async def exists(self, path: str) -> bool:
|
|
91
|
+
return await asyncio.to_thread(os.path.exists, path)
|
|
92
|
+
|
|
93
|
+
async def is_dir(self, path: str) -> bool:
|
|
94
|
+
return await asyncio.to_thread(os.path.isdir, path)
|
|
95
|
+
|
|
96
|
+
async def is_symlink(self, path: str) -> bool:
|
|
97
|
+
return await asyncio.to_thread(os.path.islink, path)
|
|
98
|
+
|
|
99
|
+
async def read_bytes(self, path: str) -> bytes:
|
|
100
|
+
return await asyncio.to_thread(_read_bytes, path)
|
|
101
|
+
|
|
102
|
+
async def write_text(self, path: str, content: str) -> None:
|
|
103
|
+
await asyncio.to_thread(_write_text, path, content)
|
|
104
|
+
|
|
105
|
+
async def write_bytes(self, path: str, data: bytes) -> None:
|
|
106
|
+
await asyncio.to_thread(_write_bytes, path, data)
|
|
107
|
+
|
|
108
|
+
async def mkdir(self, path: str) -> None:
|
|
109
|
+
await asyncio.to_thread(os.makedirs, path, exist_ok=True)
|
|
110
|
+
|
|
111
|
+
async def readdir(self, path: str) -> list[str]:
|
|
112
|
+
return await asyncio.to_thread(lambda: list(os.listdir(path)))
|
|
113
|
+
|
|
114
|
+
async def check_access(self, path: str, *, write: bool = False) -> None:
|
|
115
|
+
mode = os.R_OK | os.W_OK if write else os.R_OK
|
|
116
|
+
await asyncio.to_thread(_check_access, path, mode)
|
|
117
|
+
|
|
118
|
+
def __repr__(self) -> str:
|
|
119
|
+
return "LocalFileOperations()"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _read_bytes(path: str) -> bytes:
|
|
123
|
+
with open(path, "rb") as handle:
|
|
124
|
+
return handle.read()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _write_text(path: str, content: str) -> None:
|
|
128
|
+
# newline="" 保留内容里原有的换行符:做一次平台转换会把 CRLF 改回 LF(或者反过来)。
|
|
129
|
+
with open(path, "w", encoding="utf-8", newline="") as handle:
|
|
130
|
+
handle.write(content)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _write_bytes(path: str, data: bytes) -> None:
|
|
134
|
+
# edit 已经完成编码、BOM 与换行还原;二进制写不再引入任何平台转换。
|
|
135
|
+
with open(path, "wb") as handle:
|
|
136
|
+
handle.write(data)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _check_access(path: str, mode: int) -> None:
|
|
140
|
+
if not os.access(path, mode):
|
|
141
|
+
kind = "读写" if mode & os.W_OK else "读"
|
|
142
|
+
raise PermissionError(f"{path} 不可{kind}")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class CommandTimedOut(RuntimeError):
|
|
146
|
+
"""命令超时。携带超时秒数,供工具拼出 ``Command timed out after N seconds``。"""
|
|
147
|
+
|
|
148
|
+
def __init__(self, seconds: float) -> None:
|
|
149
|
+
super().__init__(f"timeout:{seconds:g}")
|
|
150
|
+
self.seconds = seconds
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class ShellOperations(Protocol):
|
|
154
|
+
"""命令执行。返回退出码;取消/超时用 :class:`OperationAborted` /
|
|
155
|
+
:class:`CommandTimedOut` 表达,其余失败照实抛 ``OSError``。"""
|
|
156
|
+
|
|
157
|
+
async def exec(
|
|
158
|
+
self,
|
|
159
|
+
command: str,
|
|
160
|
+
cwd: str,
|
|
161
|
+
*,
|
|
162
|
+
on_data: Callable[[bytes], None],
|
|
163
|
+
timeout: float | None,
|
|
164
|
+
signal: CancelToken | None,
|
|
165
|
+
env: Mapping[str, str] | None,
|
|
166
|
+
) -> int:
|
|
167
|
+
"""执行 ``command``,把 stdout/stderr 的字节块交给 ``on_data``。
|
|
168
|
+
|
|
169
|
+
``timeout`` 单位是秒,``None`` 表示不设超时。实现必须保证**超时与取消时杀掉
|
|
170
|
+
整个进程组**:只杀 shell 会让它启动的后台进程继续持有管道,调用方读不到 EOF。
|
|
171
|
+
"""
|
|
172
|
+
...
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class LocalShellOperations:
|
|
176
|
+
"""用 ``bash -c`` 在本机执行。``start_new_session=True`` 让命令成为新进程组的组长,
|
|
177
|
+
这样"杀一组"等价于"杀 shell 和它启动的全部子进程"。
|
|
178
|
+
|
|
179
|
+
``prefix`` 是插在 ``bash`` 之前的 argv(例如 ``sandbox-exec -p <profile>``)。
|
|
180
|
+
沙箱不需要另写一个 ``exec`` 实现:进程创建、输出泵、超时与取消杀组的逻辑只该
|
|
181
|
+
有一份,边界只是命令前面多的几个参数。
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
__slots__ = ("_prefix", "_shell")
|
|
185
|
+
|
|
186
|
+
def __init__(self, shell: str = "bash", prefix: Sequence[str] = ()) -> None:
|
|
187
|
+
self._shell = shell
|
|
188
|
+
self._prefix = tuple(prefix)
|
|
189
|
+
|
|
190
|
+
async def exec(
|
|
191
|
+
self,
|
|
192
|
+
command: str,
|
|
193
|
+
cwd: str,
|
|
194
|
+
*,
|
|
195
|
+
on_data: Callable[[bytes], None],
|
|
196
|
+
timeout: float | None,
|
|
197
|
+
signal: CancelToken | None,
|
|
198
|
+
env: Mapping[str, str] | None,
|
|
199
|
+
) -> int:
|
|
200
|
+
if not os.path.isdir(cwd):
|
|
201
|
+
raise FileNotFoundError(f"Working directory does not exist: {cwd}")
|
|
202
|
+
process = await asyncio.create_subprocess_exec(
|
|
203
|
+
*self._prefix,
|
|
204
|
+
self._shell,
|
|
205
|
+
"-c",
|
|
206
|
+
command,
|
|
207
|
+
cwd=cwd,
|
|
208
|
+
env=dict(env) if env is not None else None,
|
|
209
|
+
stdin=asyncio.subprocess.DEVNULL,
|
|
210
|
+
stdout=asyncio.subprocess.PIPE,
|
|
211
|
+
stderr=asyncio.subprocess.PIPE,
|
|
212
|
+
start_new_session=True,
|
|
213
|
+
)
|
|
214
|
+
pumps = [
|
|
215
|
+
asyncio.create_task(_pump(process.stdout, on_data)),
|
|
216
|
+
asyncio.create_task(_pump(process.stderr, on_data)),
|
|
217
|
+
]
|
|
218
|
+
timed_out: float | None = None
|
|
219
|
+
loop = asyncio.get_running_loop()
|
|
220
|
+
started = loop.time()
|
|
221
|
+
while process.returncode is None:
|
|
222
|
+
if signal is not None and signal.cancelled:
|
|
223
|
+
_kill_process_group(process.pid)
|
|
224
|
+
break
|
|
225
|
+
if timeout is not None and loop.time() - started >= timeout:
|
|
226
|
+
timed_out = timeout
|
|
227
|
+
_kill_process_group(process.pid)
|
|
228
|
+
break
|
|
229
|
+
await asyncio.sleep(_POLL_INTERVAL)
|
|
230
|
+
await process.wait()
|
|
231
|
+
await asyncio.gather(*pumps)
|
|
232
|
+
if timed_out is not None:
|
|
233
|
+
raise CommandTimedOut(timed_out)
|
|
234
|
+
if signal is not None and signal.cancelled:
|
|
235
|
+
raise OperationAborted("Command aborted")
|
|
236
|
+
code = process.returncode if process.returncode is not None else 1
|
|
237
|
+
# 被信号杀死的进程没有退出码;按 shell 惯例报 128 + 信号编号。
|
|
238
|
+
return code if code >= 0 else 128 + abs(code)
|
|
239
|
+
|
|
240
|
+
def __repr__(self) -> str:
|
|
241
|
+
prefix = f", prefix={len(self._prefix)} argv" if self._prefix else ""
|
|
242
|
+
return f"LocalShellOperations(shell={self._shell!r}{prefix})"
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
async def _pump(stream: asyncio.StreamReader | None, on_data: Callable[[bytes], None]) -> None:
|
|
246
|
+
if stream is None:
|
|
247
|
+
return
|
|
248
|
+
while True:
|
|
249
|
+
chunk = await stream.read(_READ_CHUNK)
|
|
250
|
+
if not chunk:
|
|
251
|
+
return
|
|
252
|
+
on_data(chunk)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _kill_process_group(pid: int) -> None:
|
|
256
|
+
"""杀掉以 ``pid`` 为组长的整个进程组。
|
|
257
|
+
|
|
258
|
+
``ProcessLookupError`` 是正常竞态(进程在我们动手前刚好退出),不是错误。
|
|
259
|
+
"""
|
|
260
|
+
try:
|
|
261
|
+
os.killpg(os.getpgid(pid), signal_module.SIGKILL)
|
|
262
|
+
except ProcessLookupError:
|
|
263
|
+
return
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
__all__ = [
|
|
267
|
+
"CommandTimedOut",
|
|
268
|
+
"FileOperations",
|
|
269
|
+
"LocalFileOperations",
|
|
270
|
+
"LocalShellOperations",
|
|
271
|
+
"OperationAborted",
|
|
272
|
+
"ShellOperations",
|
|
273
|
+
"ensure_not_cancelled",
|
|
274
|
+
]
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""命令输出的增量累积:只留尾部、超限落盘。
|
|
2
|
+
|
|
3
|
+
一条 ``bash`` 命令可能吐出几百 MB
|
|
4
|
+
(``yes``、日志、``find /``),三条约束同时成立:
|
|
5
|
+
|
|
6
|
+
1. **内存有界**:只保留最后约 ``4 × max_bytes`` 的文本用于快照,更早的内容丢弃;
|
|
7
|
+
2. **完整输出可找回**:一旦总量超过上限,就把**原始字节**写进文件,结果里给出路径;
|
|
8
|
+
3. **行数/字节数准确**:模型看到的 ``[Showing lines 1998-2000 of 2000 …]`` 必须是真的,
|
|
9
|
+
所以统计在累积时做,不靠事后数快照。
|
|
10
|
+
|
|
11
|
+
## 文件放在哪里由调用方决定
|
|
12
|
+
|
|
13
|
+
向 :class:`ToolOutputStore` 申请路径:目录、数量上限与保留期都由仓库管,累积器只负责写。
|
|
14
|
+
这样"谁创建、谁保留多久"只有一个答案,不会散落在工具实现里。
|
|
15
|
+
|
|
16
|
+
## 为什么同时留原始字节与解码文本
|
|
17
|
+
|
|
18
|
+
原始字节是"完整输出文件"的唯一可靠来源(解码再编码不是恒等变换),解码文本只用于
|
|
19
|
+
展示。
|
|
20
|
+
|
|
21
|
+
## 分块边界上的半个字符
|
|
22
|
+
|
|
23
|
+
``bytes.decode`` 在多字节字符中间切断会抛错或产出替换符。用**增量解码器**:它把不完整
|
|
24
|
+
的尾字节留在内部缓冲里,等下一块到齐再一起产出。命令结束时 ``finish()`` 冲掉残留
|
|
25
|
+
(那里确实是不完整序列,替换成 ``�`` 是唯一诚实的输出)。
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import codecs
|
|
31
|
+
import os
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from typing import IO, Final
|
|
34
|
+
|
|
35
|
+
from braid_coding_agent.tools.output_store import ToolOutputStore
|
|
36
|
+
from braid_coding_agent.tools.truncate import (
|
|
37
|
+
DEFAULT_MAX_BYTES,
|
|
38
|
+
DEFAULT_MAX_LINES,
|
|
39
|
+
TruncationResult,
|
|
40
|
+
byte_length,
|
|
41
|
+
truncate_tail,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
#: ``read_full_output`` 的默认上限:1MB。完整输出是给程序化调用方的,不是给模型的。
|
|
45
|
+
STRUCTURED_OUTPUT_MAX_BYTES: Final[int] = 1024 * 1024
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(slots=True, frozen=True)
|
|
49
|
+
class OutputSnapshot:
|
|
50
|
+
"""某一刻的展示快照:尾部文本、截断账目、完整输出文件路径(若已落盘)。"""
|
|
51
|
+
|
|
52
|
+
content: str
|
|
53
|
+
truncation: TruncationResult
|
|
54
|
+
full_output_path: str | None = None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(slots=True, frozen=True)
|
|
58
|
+
class FullOutput:
|
|
59
|
+
"""完整输出(可能被"掐头留尾")。``truncated`` 为真表示中间有一段被省略。"""
|
|
60
|
+
|
|
61
|
+
content: str
|
|
62
|
+
truncated: bool
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class OutputAccumulator:
|
|
66
|
+
"""一边收字节一边维护尾部快照与统计。只在事件循环线程里用。"""
|
|
67
|
+
|
|
68
|
+
__slots__ = (
|
|
69
|
+
"_completed_lines",
|
|
70
|
+
"_current_line_bytes",
|
|
71
|
+
"_decoder",
|
|
72
|
+
"_finished",
|
|
73
|
+
"_has_open_line",
|
|
74
|
+
"_max_bytes",
|
|
75
|
+
"_max_lines",
|
|
76
|
+
"_raw_chunks",
|
|
77
|
+
"_store",
|
|
78
|
+
"_tail_bytes",
|
|
79
|
+
"_tail_text",
|
|
80
|
+
"_temp_file",
|
|
81
|
+
"_temp_path",
|
|
82
|
+
"_temp_prefix",
|
|
83
|
+
"_total_decoded_bytes",
|
|
84
|
+
"_total_lines",
|
|
85
|
+
"_total_raw_bytes",
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
*,
|
|
91
|
+
store: ToolOutputStore,
|
|
92
|
+
max_lines: int = DEFAULT_MAX_LINES,
|
|
93
|
+
max_bytes: int = DEFAULT_MAX_BYTES,
|
|
94
|
+
temp_prefix: str = "braid-bash",
|
|
95
|
+
) -> None:
|
|
96
|
+
self._max_lines = max_lines
|
|
97
|
+
self._max_bytes = max_bytes
|
|
98
|
+
self._temp_prefix = temp_prefix
|
|
99
|
+
self._store = store
|
|
100
|
+
self._decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
|
|
101
|
+
self._raw_chunks: list[bytes] = []
|
|
102
|
+
self._tail_text = ""
|
|
103
|
+
self._tail_bytes = 0
|
|
104
|
+
self._total_raw_bytes = 0
|
|
105
|
+
self._total_decoded_bytes = 0
|
|
106
|
+
self._completed_lines = 0
|
|
107
|
+
self._total_lines = 0
|
|
108
|
+
self._current_line_bytes = 0
|
|
109
|
+
self._has_open_line = False
|
|
110
|
+
self._finished = False
|
|
111
|
+
self._temp_file: IO[bytes] | None = None
|
|
112
|
+
self._temp_path: str | None = None
|
|
113
|
+
|
|
114
|
+
# ------------------------------------------------------------- 写入
|
|
115
|
+
|
|
116
|
+
def append(self, data: bytes) -> None:
|
|
117
|
+
"""接一块原始输出。超过上限后自动开始落盘。"""
|
|
118
|
+
self._total_raw_bytes += len(data)
|
|
119
|
+
self._append_text(self._decoder.decode(data, False))
|
|
120
|
+
if self._temp_path is not None:
|
|
121
|
+
self._write_temp(data)
|
|
122
|
+
elif self._should_use_temp_file():
|
|
123
|
+
self._ensure_temp_file()
|
|
124
|
+
self._write_temp(data)
|
|
125
|
+
elif data:
|
|
126
|
+
self._raw_chunks.append(data)
|
|
127
|
+
|
|
128
|
+
def finish(self) -> None:
|
|
129
|
+
"""命令结束:冲掉增量解码器的残留字节,必要时补建临时文件。"""
|
|
130
|
+
if self._finished:
|
|
131
|
+
return
|
|
132
|
+
self._finished = True
|
|
133
|
+
self._append_text(self._decoder.decode(b"", True))
|
|
134
|
+
if self._should_use_temp_file():
|
|
135
|
+
self._ensure_temp_file()
|
|
136
|
+
|
|
137
|
+
# ------------------------------------------------------------- 快照
|
|
138
|
+
|
|
139
|
+
def snapshot(self, *, persist_if_truncated: bool = False) -> OutputSnapshot:
|
|
140
|
+
"""取当前展示快照。``persist_if_truncated`` 为真时,只要发生截断就落盘。"""
|
|
141
|
+
tail = truncate_tail(self._tail_text, max_lines=self._max_lines, max_bytes=self._max_bytes)
|
|
142
|
+
truncated = (
|
|
143
|
+
self._total_lines > self._max_lines or self._total_decoded_bytes > self._max_bytes
|
|
144
|
+
)
|
|
145
|
+
if not truncated:
|
|
146
|
+
truncated_by = None
|
|
147
|
+
elif tail.truncated_by is not None:
|
|
148
|
+
truncated_by = tail.truncated_by
|
|
149
|
+
else:
|
|
150
|
+
truncated_by = "bytes" if self._total_decoded_bytes > self._max_bytes else "lines"
|
|
151
|
+
truncation = TruncationResult(
|
|
152
|
+
content=tail.content,
|
|
153
|
+
truncated=truncated,
|
|
154
|
+
truncated_by=truncated_by,
|
|
155
|
+
total_lines=self._total_lines,
|
|
156
|
+
total_bytes=self._total_decoded_bytes,
|
|
157
|
+
output_lines=tail.output_lines,
|
|
158
|
+
output_bytes=tail.output_bytes,
|
|
159
|
+
last_line_partial=tail.last_line_partial,
|
|
160
|
+
first_line_exceeds_limit=False,
|
|
161
|
+
max_lines=self._max_lines,
|
|
162
|
+
max_bytes=self._max_bytes,
|
|
163
|
+
)
|
|
164
|
+
if persist_if_truncated and truncated:
|
|
165
|
+
self._ensure_temp_file()
|
|
166
|
+
return OutputSnapshot(
|
|
167
|
+
content=truncation.content,
|
|
168
|
+
truncation=truncation,
|
|
169
|
+
full_output_path=self._temp_path,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
def read_full_output(self, max_bytes: int = STRUCTURED_OUTPUT_MAX_BYTES) -> FullOutput:
|
|
173
|
+
"""完整输出。只在 :meth:`finish` 与 :meth:`close` 之后调用。
|
|
174
|
+
|
|
175
|
+
超过 ``max_bytes`` 时保留头尾各一半,中间写一段省略说明:程序化调用方要的是
|
|
176
|
+
"能不能 grep 到关键行",不是几十 MB 的原文。
|
|
177
|
+
"""
|
|
178
|
+
if self._temp_path is None:
|
|
179
|
+
return FullOutput(
|
|
180
|
+
content=b"".join(self._raw_chunks).decode("utf-8", errors="replace"),
|
|
181
|
+
truncated=False,
|
|
182
|
+
)
|
|
183
|
+
size = os.path.getsize(self._temp_path)
|
|
184
|
+
if size <= max_bytes:
|
|
185
|
+
with open(self._temp_path, "rb") as handle:
|
|
186
|
+
return FullOutput(handle.read().decode("utf-8", errors="replace"), truncated=False)
|
|
187
|
+
head_size = max_bytes // 2
|
|
188
|
+
tail_size = max_bytes - head_size
|
|
189
|
+
with open(self._temp_path, "rb") as handle:
|
|
190
|
+
head = handle.read(head_size)
|
|
191
|
+
handle.seek(size - tail_size)
|
|
192
|
+
tail = handle.read(tail_size)
|
|
193
|
+
# errors="ignore" 分别丢掉"被切断的尾序列"与"开头的续字节",正好是拼接需要的语义。
|
|
194
|
+
return FullOutput(
|
|
195
|
+
content=(
|
|
196
|
+
f"{head.decode('utf-8', errors='ignore')}\n\n"
|
|
197
|
+
f"[... {size - max_bytes} bytes omitted ...]\n\n"
|
|
198
|
+
f"{tail.decode('utf-8', errors='ignore')}"
|
|
199
|
+
),
|
|
200
|
+
truncated=True,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
def close(self) -> None:
|
|
204
|
+
"""关闭文件并把"写完了"告诉仓库。可重复调用。"""
|
|
205
|
+
handle = self._temp_file
|
|
206
|
+
self._temp_file = None
|
|
207
|
+
if handle is not None:
|
|
208
|
+
handle.close()
|
|
209
|
+
if self._temp_path is not None:
|
|
210
|
+
self._store.close_output_file(self._temp_path)
|
|
211
|
+
|
|
212
|
+
def last_line_bytes(self) -> int:
|
|
213
|
+
"""最后一行(可能还没写完)的字节数。用于"整行被截断"的提示。"""
|
|
214
|
+
return self._current_line_bytes
|
|
215
|
+
|
|
216
|
+
# ------------------------------------------------------------- 内部
|
|
217
|
+
|
|
218
|
+
def _append_text(self, text: str) -> None:
|
|
219
|
+
if not text:
|
|
220
|
+
return
|
|
221
|
+
size = byte_length(text)
|
|
222
|
+
self._total_decoded_bytes += size
|
|
223
|
+
self._tail_text += text
|
|
224
|
+
self._tail_bytes += size
|
|
225
|
+
if self._tail_bytes > self._max_bytes * 4:
|
|
226
|
+
self._trim_tail()
|
|
227
|
+
|
|
228
|
+
newlines = text.count("\n")
|
|
229
|
+
if newlines == 0:
|
|
230
|
+
self._current_line_bytes += size
|
|
231
|
+
self._has_open_line = True
|
|
232
|
+
else:
|
|
233
|
+
last = text.rfind("\n")
|
|
234
|
+
self._completed_lines += newlines
|
|
235
|
+
self._current_line_bytes = byte_length(text[last + 1 :])
|
|
236
|
+
self._has_open_line = last + 1 < len(text)
|
|
237
|
+
self._total_lines = self._completed_lines + (1 if self._has_open_line else 0)
|
|
238
|
+
|
|
239
|
+
def _trim_tail(self) -> None:
|
|
240
|
+
"""把尾部文本裁到 ``2 × max_bytes`` 以内,并丢掉被切断的半行。"""
|
|
241
|
+
raw = self._tail_text.encode("utf-8")
|
|
242
|
+
keep = self._max_bytes * 2
|
|
243
|
+
start = len(raw) - keep
|
|
244
|
+
# 0b10xxxxxx 是续字节:往后挪到字符边界,否则 decode 会产出替换符。
|
|
245
|
+
while start < len(raw) and (raw[start] & 0xC0) == 0x80:
|
|
246
|
+
start += 1
|
|
247
|
+
text = raw[start:].decode("utf-8")
|
|
248
|
+
newline = text.find("\n")
|
|
249
|
+
if newline != -1:
|
|
250
|
+
text = text[newline + 1 :]
|
|
251
|
+
self._tail_text = text
|
|
252
|
+
self._tail_bytes = byte_length(text)
|
|
253
|
+
|
|
254
|
+
def _should_use_temp_file(self) -> bool:
|
|
255
|
+
return (
|
|
256
|
+
self._total_raw_bytes > self._max_bytes
|
|
257
|
+
or self._total_decoded_bytes > self._max_bytes
|
|
258
|
+
or self._total_lines > self._max_lines
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def _ensure_temp_file(self) -> None:
|
|
262
|
+
if self._temp_path is not None:
|
|
263
|
+
return
|
|
264
|
+
path, descriptor = self._store.open_output_file(self._temp_prefix)
|
|
265
|
+
self._temp_path = path
|
|
266
|
+
self._temp_file = os.fdopen(descriptor, "wb")
|
|
267
|
+
for chunk in self._raw_chunks:
|
|
268
|
+
self._write_temp(chunk)
|
|
269
|
+
self._raw_chunks.clear()
|
|
270
|
+
|
|
271
|
+
def _write_temp(self, data: bytes) -> None:
|
|
272
|
+
handle = self._temp_file
|
|
273
|
+
assert handle is not None, "临时文件尚未创建"
|
|
274
|
+
handle.write(data)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
__all__ = [
|
|
278
|
+
"STRUCTURED_OUTPUT_MAX_BYTES",
|
|
279
|
+
"FullOutput",
|
|
280
|
+
"OutputAccumulator",
|
|
281
|
+
"OutputSnapshot",
|
|
282
|
+
]
|