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,347 @@
|
|
|
1
|
+
"""后台任务调度:优先级、并发上限、超时、取消、重试与协作式资源记账。
|
|
2
|
+
|
|
3
|
+
异步只表示不阻塞调用方,不表示不消耗 CPU 与磁盘。启动阶段同时扫描技能目录、
|
|
4
|
+
连接多个 MCP 服务器、读取项目信息时,需要限制同时在跑的任务数,并让每次任务
|
|
5
|
+
结束后主动让出事件循环,交互输入才有机会插进来。
|
|
6
|
+
|
|
7
|
+
调度器不替任务做 OS 级资源隔离;CPU 配额由沙箱或外部进程限制负责,这里记录
|
|
8
|
+
每个任务的 CPU 时间并在超过预算时计数,供 ``/monitor`` 观察后台是否干扰交互。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import inspect
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import Awaitable, Callable
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from enum import IntEnum
|
|
19
|
+
from typing import Literal
|
|
20
|
+
|
|
21
|
+
from braid_coding_agent.startup.monitor import StartupMonitor
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"BackgroundScheduler",
|
|
25
|
+
"ScheduledTask",
|
|
26
|
+
"SchedulerFullError",
|
|
27
|
+
"TaskPriority",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
type TaskState = Literal["pending", "running", "succeeded", "failed", "cancelled", "timed_out"]
|
|
31
|
+
type TaskPolicy = Literal["required", "eager", "lazy", "manual"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class TaskPriority(IntEnum):
|
|
35
|
+
"""数值越小越先执行。安全检查永远排在功能预热之前。"""
|
|
36
|
+
|
|
37
|
+
CRITICAL = 0
|
|
38
|
+
EAGER = 10
|
|
39
|
+
NORMAL = 20
|
|
40
|
+
LAZY = 30
|
|
41
|
+
MANUAL = 40
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SchedulerFullError(RuntimeError):
|
|
45
|
+
"""未完成任务数达到上限。调用方应当减少任务或提高上限。"""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(slots=True, frozen=True)
|
|
49
|
+
class ScheduledTask:
|
|
50
|
+
"""一次提交的只读快照。``error`` 只在失败或超时时非空。"""
|
|
51
|
+
|
|
52
|
+
name: str
|
|
53
|
+
priority: TaskPriority
|
|
54
|
+
policy: TaskPolicy
|
|
55
|
+
state: TaskState
|
|
56
|
+
attempts: int = 0
|
|
57
|
+
duration_ms: float = 0.0
|
|
58
|
+
cpu_ms: float = 0.0
|
|
59
|
+
error: str | None = None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(slots=True)
|
|
63
|
+
class _Queued:
|
|
64
|
+
name: str
|
|
65
|
+
priority: TaskPriority
|
|
66
|
+
policy: TaskPolicy
|
|
67
|
+
factory: Callable[[], Awaitable[None] | None]
|
|
68
|
+
timeout_s: float | None
|
|
69
|
+
retries: int
|
|
70
|
+
sequence: int
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(slots=True)
|
|
74
|
+
class _State:
|
|
75
|
+
queued: _Queued
|
|
76
|
+
state: TaskState = "pending"
|
|
77
|
+
attempts: int = 0
|
|
78
|
+
started: float = 0.0
|
|
79
|
+
duration_ms: float = 0.0
|
|
80
|
+
cpu_ms: float = 0.0
|
|
81
|
+
error: str | None = None
|
|
82
|
+
handle: asyncio.Task[None] | None = None
|
|
83
|
+
cancel_requested: bool = False
|
|
84
|
+
|
|
85
|
+
def snapshot(self) -> ScheduledTask:
|
|
86
|
+
return ScheduledTask(
|
|
87
|
+
name=self.queued.name,
|
|
88
|
+
priority=self.queued.priority,
|
|
89
|
+
policy=self.queued.policy,
|
|
90
|
+
state=self.state,
|
|
91
|
+
attempts=self.attempts,
|
|
92
|
+
duration_ms=self.duration_ms,
|
|
93
|
+
cpu_ms=self.cpu_ms,
|
|
94
|
+
error=self.error,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class BackgroundScheduler:
|
|
99
|
+
"""固定数量 worker 消费的优先级队列。
|
|
100
|
+
|
|
101
|
+
:param concurrency: 同时执行的任务数上限。
|
|
102
|
+
:param max_pending: 未完成任务数上限,包含排队与运行中的任务。
|
|
103
|
+
:param retry_backoff_s: 第 N 次重试前等待 ``N * retry_backoff_s`` 秒。
|
|
104
|
+
:param yield_delay_s: 每个任务结束后主动让出事件循环的时间。
|
|
105
|
+
:param cpu_budget_ms: 单个任务的协作式 CPU 预算,超出只记数不强制终止。
|
|
106
|
+
:param on_failure: 后台失败回调,CLI 用它把错误写到 stderr。
|
|
107
|
+
:param on_change: 任务状态变化回调,界面用它做批量刷新。
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
def __init__(
|
|
111
|
+
self,
|
|
112
|
+
*,
|
|
113
|
+
concurrency: int = 4,
|
|
114
|
+
max_pending: int = 64,
|
|
115
|
+
retry_backoff_s: float = 0.05,
|
|
116
|
+
yield_delay_s: float = 0.001,
|
|
117
|
+
cpu_budget_ms: float | None = None,
|
|
118
|
+
monitor: StartupMonitor | None = None,
|
|
119
|
+
on_failure: Callable[[ScheduledTask], None] | None = None,
|
|
120
|
+
on_change: Callable[[ScheduledTask], None] | None = None,
|
|
121
|
+
) -> None:
|
|
122
|
+
if concurrency < 1:
|
|
123
|
+
raise ValueError("并发上限至少为 1")
|
|
124
|
+
if max_pending < concurrency:
|
|
125
|
+
raise ValueError("未完成任务上限不能小于并发上限")
|
|
126
|
+
self._concurrency = concurrency
|
|
127
|
+
self._max_pending = max_pending
|
|
128
|
+
self._retry_backoff_s = retry_backoff_s
|
|
129
|
+
self._yield_delay_s = yield_delay_s
|
|
130
|
+
self._cpu_budget_ms = cpu_budget_ms
|
|
131
|
+
self._monitor = monitor
|
|
132
|
+
self._on_failure = on_failure
|
|
133
|
+
self._listeners: list[Callable[[ScheduledTask], None]] = []
|
|
134
|
+
if on_change is not None:
|
|
135
|
+
self._listeners.append(on_change)
|
|
136
|
+
self._queue: asyncio.PriorityQueue[tuple[int, int, _Queued]] = asyncio.PriorityQueue()
|
|
137
|
+
self._states: dict[str, _State] = {}
|
|
138
|
+
self._workers: list[asyncio.Task[None]] = []
|
|
139
|
+
self._sequence = 0
|
|
140
|
+
self._running = 0
|
|
141
|
+
self._started = False
|
|
142
|
+
self._idle = asyncio.Event()
|
|
143
|
+
self._idle.set()
|
|
144
|
+
|
|
145
|
+
async def start(self) -> None:
|
|
146
|
+
"""启动 worker。重复调用无副作用。"""
|
|
147
|
+
if self._started:
|
|
148
|
+
return
|
|
149
|
+
self._started = True
|
|
150
|
+
self._workers = [
|
|
151
|
+
asyncio.create_task(self._work(), name=f"braid-startup-{index}")
|
|
152
|
+
for index in range(self._concurrency)
|
|
153
|
+
]
|
|
154
|
+
|
|
155
|
+
def subscribe(self, listener: Callable[[ScheduledTask], None]) -> Callable[[], None]:
|
|
156
|
+
"""注册任务状态变化回调,返回退订函数。界面用它合并刷新。"""
|
|
157
|
+
self._listeners.append(listener)
|
|
158
|
+
|
|
159
|
+
def unsubscribe() -> None:
|
|
160
|
+
if listener in self._listeners:
|
|
161
|
+
self._listeners.remove(listener)
|
|
162
|
+
|
|
163
|
+
return unsubscribe
|
|
164
|
+
|
|
165
|
+
def submit(
|
|
166
|
+
self,
|
|
167
|
+
name: str,
|
|
168
|
+
factory: Callable[[], Awaitable[None] | None],
|
|
169
|
+
*,
|
|
170
|
+
priority: TaskPriority = TaskPriority.NORMAL,
|
|
171
|
+
policy: TaskPolicy = "eager",
|
|
172
|
+
timeout_s: float | None = 30.0,
|
|
173
|
+
retries: int = 0,
|
|
174
|
+
) -> None:
|
|
175
|
+
"""提交一个任务。重名且未完成的任务按调用错误处理。"""
|
|
176
|
+
if not self._started:
|
|
177
|
+
raise RuntimeError("调度器还没有启动:先 await scheduler.start()")
|
|
178
|
+
if name in self._states and self._states[name].state in ("pending", "running"):
|
|
179
|
+
raise ValueError(f"后台任务 {name!r} 已经在运行")
|
|
180
|
+
active = sum(1 for state in self._states.values() if state.state in ("pending", "running"))
|
|
181
|
+
if active >= self._max_pending:
|
|
182
|
+
raise SchedulerFullError(f"后台任务数已达上限 {self._max_pending};先等待现有任务完成")
|
|
183
|
+
self._sequence += 1
|
|
184
|
+
queued = _Queued(
|
|
185
|
+
name=name,
|
|
186
|
+
priority=priority,
|
|
187
|
+
policy=policy,
|
|
188
|
+
factory=factory,
|
|
189
|
+
timeout_s=timeout_s,
|
|
190
|
+
retries=max(retries, 0),
|
|
191
|
+
sequence=self._sequence,
|
|
192
|
+
)
|
|
193
|
+
state = _State(queued=queued)
|
|
194
|
+
self._states[name] = state
|
|
195
|
+
self._idle.clear()
|
|
196
|
+
self._queue.put_nowait((int(priority), queued.sequence, queued))
|
|
197
|
+
self._notify(state)
|
|
198
|
+
if self._monitor is not None:
|
|
199
|
+
self._monitor.increment("tasks_submitted")
|
|
200
|
+
|
|
201
|
+
async def wait_idle(self) -> None:
|
|
202
|
+
"""等到队列为空且没有任务在运行。"""
|
|
203
|
+
while self._has_active():
|
|
204
|
+
await self._idle.wait()
|
|
205
|
+
self._idle.clear()
|
|
206
|
+
|
|
207
|
+
def snapshot(self) -> tuple[ScheduledTask, ...]:
|
|
208
|
+
"""按提交顺序返回任务快照。"""
|
|
209
|
+
return tuple(
|
|
210
|
+
state.snapshot()
|
|
211
|
+
for state in sorted(self._states.values(), key=lambda item: item.queued.sequence)
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def cancel(self, name: str) -> bool:
|
|
215
|
+
"""取消一个排队或运行中的任务。返回是否找到可取消的任务。"""
|
|
216
|
+
state = self._states.get(name)
|
|
217
|
+
if state is None or state.state not in ("pending", "running"):
|
|
218
|
+
return False
|
|
219
|
+
state.cancel_requested = True
|
|
220
|
+
if state.handle is not None:
|
|
221
|
+
state.handle.cancel()
|
|
222
|
+
else:
|
|
223
|
+
state.state = "cancelled"
|
|
224
|
+
self._notify(state)
|
|
225
|
+
self._maybe_idle()
|
|
226
|
+
return True
|
|
227
|
+
|
|
228
|
+
async def shutdown(self) -> None:
|
|
229
|
+
"""停止 worker;排队中的任务标记为取消。"""
|
|
230
|
+
for state in self._states.values():
|
|
231
|
+
if state.state == "pending":
|
|
232
|
+
state.state = "cancelled"
|
|
233
|
+
self._notify(state)
|
|
234
|
+
if state.handle is not None and not state.handle.done():
|
|
235
|
+
state.handle.cancel()
|
|
236
|
+
for worker in self._workers:
|
|
237
|
+
worker.cancel()
|
|
238
|
+
await asyncio.gather(*self._workers, return_exceptions=True)
|
|
239
|
+
self._workers = []
|
|
240
|
+
self._started = False
|
|
241
|
+
self._maybe_idle()
|
|
242
|
+
|
|
243
|
+
# ------------------------------------------------------------------ 内部
|
|
244
|
+
|
|
245
|
+
async def _work(self) -> None:
|
|
246
|
+
while True:
|
|
247
|
+
priority, sequence, queued = await self._queue.get()
|
|
248
|
+
del priority, sequence
|
|
249
|
+
state = self._states[queued.name]
|
|
250
|
+
if state.cancel_requested:
|
|
251
|
+
state.state = "cancelled"
|
|
252
|
+
self._queue.task_done()
|
|
253
|
+
self._notify(state)
|
|
254
|
+
self._maybe_idle()
|
|
255
|
+
continue
|
|
256
|
+
self._running += 1
|
|
257
|
+
state.state = "running"
|
|
258
|
+
state.started = time.perf_counter()
|
|
259
|
+
cpu_started = time.process_time()
|
|
260
|
+
self._notify(state)
|
|
261
|
+
try:
|
|
262
|
+
while True:
|
|
263
|
+
state.attempts += 1
|
|
264
|
+
state.handle = asyncio.create_task(
|
|
265
|
+
self._invoke(queued.factory), name=f"braid-task-{queued.name}"
|
|
266
|
+
)
|
|
267
|
+
try:
|
|
268
|
+
if queued.timeout_s is None:
|
|
269
|
+
await state.handle
|
|
270
|
+
else:
|
|
271
|
+
await asyncio.wait_for(state.handle, queued.timeout_s)
|
|
272
|
+
except TimeoutError:
|
|
273
|
+
state.state = "timed_out"
|
|
274
|
+
state.error = f"超过 {queued.timeout_s:g} 秒未完成"
|
|
275
|
+
break
|
|
276
|
+
except asyncio.CancelledError:
|
|
277
|
+
current = asyncio.current_task()
|
|
278
|
+
if current is not None and current.cancelling():
|
|
279
|
+
raise
|
|
280
|
+
state.state = "cancelled"
|
|
281
|
+
state.error = "任务被取消"
|
|
282
|
+
break
|
|
283
|
+
except Exception as exc:
|
|
284
|
+
state.error = str(exc) or type(exc).__name__
|
|
285
|
+
if state.attempts <= queued.retries:
|
|
286
|
+
await asyncio.sleep(self._retry_backoff_s * state.attempts)
|
|
287
|
+
continue
|
|
288
|
+
state.state = "failed"
|
|
289
|
+
break
|
|
290
|
+
else:
|
|
291
|
+
state.state = "succeeded"
|
|
292
|
+
break
|
|
293
|
+
finally:
|
|
294
|
+
state.duration_ms = (time.perf_counter() - state.started) * 1000.0
|
|
295
|
+
state.cpu_ms = (time.process_time() - cpu_started) * 1000.0
|
|
296
|
+
self._record_cpu(state)
|
|
297
|
+
state.handle = None
|
|
298
|
+
self._running -= 1
|
|
299
|
+
self._queue.task_done()
|
|
300
|
+
self._finish(state)
|
|
301
|
+
await asyncio.sleep(self._yield_delay_s)
|
|
302
|
+
|
|
303
|
+
async def _invoke(self, factory: Callable[[], Awaitable[None] | None]) -> None:
|
|
304
|
+
outcome = factory()
|
|
305
|
+
if inspect.isawaitable(outcome):
|
|
306
|
+
await outcome
|
|
307
|
+
|
|
308
|
+
def _record_cpu(self, state: _State) -> None:
|
|
309
|
+
# 任务 CPU 时间只能通过进程级 process_time 的差值近似归属。并发任务会互相
|
|
310
|
+
# 串扰,这里把它当作上限估计,供 /monitor 判断后台是否明显抢占交互。
|
|
311
|
+
if self._monitor is None:
|
|
312
|
+
return
|
|
313
|
+
self._monitor.metric(f"task.{state.queued.name}.duration_ms", state.duration_ms)
|
|
314
|
+
self._monitor.metric(f"task.{state.queued.name}.cpu_ms", state.cpu_ms)
|
|
315
|
+
previous = self._monitor.metric_value("background_cpu_ms")
|
|
316
|
+
self._monitor.metric("background_cpu_ms", previous + state.cpu_ms)
|
|
317
|
+
if self._cpu_budget_ms is not None and state.cpu_ms > self._cpu_budget_ms:
|
|
318
|
+
self._monitor.increment("task_cpu_over_budget")
|
|
319
|
+
|
|
320
|
+
def _finish(self, state: _State) -> None:
|
|
321
|
+
if state.state == "succeeded":
|
|
322
|
+
if self._monitor is not None:
|
|
323
|
+
self._monitor.increment("tasks_succeeded")
|
|
324
|
+
else:
|
|
325
|
+
if self._monitor is not None:
|
|
326
|
+
self._monitor.increment(f"tasks_{state.state}")
|
|
327
|
+
if self._on_failure is not None:
|
|
328
|
+
self._on_failure(state.snapshot())
|
|
329
|
+
if self._monitor is not None:
|
|
330
|
+
self._monitor.mark(
|
|
331
|
+
f"task.{state.queued.name}",
|
|
332
|
+
detail=state.state,
|
|
333
|
+
)
|
|
334
|
+
self._notify(state)
|
|
335
|
+
self._maybe_idle()
|
|
336
|
+
|
|
337
|
+
def _notify(self, state: _State) -> None:
|
|
338
|
+
snapshot = state.snapshot()
|
|
339
|
+
for listener in tuple(self._listeners):
|
|
340
|
+
listener(snapshot)
|
|
341
|
+
|
|
342
|
+
def _has_active(self) -> bool:
|
|
343
|
+
return self._running > 0 or any(state.state == "pending" for state in self._states.values())
|
|
344
|
+
|
|
345
|
+
def _maybe_idle(self) -> None:
|
|
346
|
+
if not self._has_active():
|
|
347
|
+
self._idle.set()
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""状态栏字段:注册表、参数解析与纯文本拼接。
|
|
2
|
+
|
|
3
|
+
REPL 与 TUI 共用这一层。字段名、顺序与显示文本在这里定义,终端渲染只负责
|
|
4
|
+
宽度与颜色;同一个字段不会在两边叫两个名字。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Final
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"DEFAULT_STATUS_FIELDS",
|
|
15
|
+
"STATUS_FIELDS",
|
|
16
|
+
"STATUS_FIELD_KEYS",
|
|
17
|
+
"StatusField",
|
|
18
|
+
"StatusLineValues",
|
|
19
|
+
"format_token_count",
|
|
20
|
+
"parse_status_fields",
|
|
21
|
+
"render_status_line",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(slots=True, frozen=True)
|
|
26
|
+
class StatusField:
|
|
27
|
+
"""状态栏的一个可选字段:键名与一句话说明。"""
|
|
28
|
+
|
|
29
|
+
key: str
|
|
30
|
+
summary: str
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(slots=True, frozen=True)
|
|
34
|
+
class StatusLineValues:
|
|
35
|
+
"""一次状态栏渲染需要的全部数值。缺省值让调用方只填自己有的字段。"""
|
|
36
|
+
|
|
37
|
+
model: str
|
|
38
|
+
context_percent: float
|
|
39
|
+
cost: float = 0.0
|
|
40
|
+
tool_count: int = 0
|
|
41
|
+
permission: str = ""
|
|
42
|
+
plan: str = ""
|
|
43
|
+
background: int = 0
|
|
44
|
+
used_tokens: int | None = None
|
|
45
|
+
context_remaining: int | None = None
|
|
46
|
+
context_window: int | None = None
|
|
47
|
+
cache_hit: float | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
#: 默认显示顺序。前七项也是 ``/statusline`` 不带参数时展示的当前字段。
|
|
51
|
+
DEFAULT_STATUS_FIELDS: Final[tuple[str, ...]] = (
|
|
52
|
+
"model",
|
|
53
|
+
"context-used",
|
|
54
|
+
"cost",
|
|
55
|
+
"tools",
|
|
56
|
+
"permission",
|
|
57
|
+
"plan",
|
|
58
|
+
"background",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
#: 全部字段。默认字段排在最前,后面是可选的上下文细节。
|
|
62
|
+
STATUS_FIELDS: Final[tuple[StatusField, ...]] = (
|
|
63
|
+
StatusField("model", "当前模型,provider/id"),
|
|
64
|
+
StatusField("context-used", "上下文占用百分比"),
|
|
65
|
+
StatusField("cost", "累计费用(美元)"),
|
|
66
|
+
StatusField("tools", "可执行工具数量"),
|
|
67
|
+
StatusField("permission", "权限模式"),
|
|
68
|
+
StatusField("plan", "计划进度或规划模式"),
|
|
69
|
+
StatusField("background", "后台子代理数量"),
|
|
70
|
+
StatusField("context-remaining", "距离上下文窗口上限的剩余 token"),
|
|
71
|
+
StatusField("context-window", "模型上下文窗口大小"),
|
|
72
|
+
StatusField("used-tokens", "当前上下文已用 token"),
|
|
73
|
+
StatusField("cache-hit", "输入侧缓存命中率"),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
STATUS_FIELD_KEYS: Final[frozenset[str]] = frozenset(field.key for field in STATUS_FIELDS)
|
|
77
|
+
|
|
78
|
+
_SEPARATORS = re.compile(r"[,,、\s]+")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def parse_status_fields(text: str) -> tuple[str, ...]:
|
|
82
|
+
"""把用户输入解析成字段元组。
|
|
83
|
+
|
|
84
|
+
逗号、中文逗号、顿号与空白都当分隔符。未知字段与重复字段直接报错:
|
|
85
|
+
静默丢掉一个字段会让用户以为配置生效了。
|
|
86
|
+
"""
|
|
87
|
+
names = tuple(name for name in _SEPARATORS.split(text.strip()) if name)
|
|
88
|
+
if not names:
|
|
89
|
+
raise ValueError("状态栏至少保留一个字段")
|
|
90
|
+
unknown = [name for name in names if name not in STATUS_FIELD_KEYS]
|
|
91
|
+
if unknown:
|
|
92
|
+
raise ValueError(
|
|
93
|
+
f"未知的状态栏字段:{'、'.join(unknown)};"
|
|
94
|
+
f"可用字段:{', '.join(field.key for field in STATUS_FIELDS)}"
|
|
95
|
+
)
|
|
96
|
+
duplicates = [name for name in dict.fromkeys(names) if names.count(name) > 1]
|
|
97
|
+
if duplicates:
|
|
98
|
+
raise ValueError(f"状态栏字段不能重复:{'、'.join(duplicates)}")
|
|
99
|
+
return names
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def format_token_count(value: int) -> str:
|
|
103
|
+
"""token 数的紧凑写法:一万二千三百写成 ``12.3k``。"""
|
|
104
|
+
if abs(value) < 1_000:
|
|
105
|
+
return str(value)
|
|
106
|
+
if abs(value) < 1_000_000:
|
|
107
|
+
return f"{value / 1_000:.1f}k"
|
|
108
|
+
return f"{value / 1_000_000:.1f}M"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def render_status_line(
|
|
112
|
+
values: StatusLineValues,
|
|
113
|
+
fields: tuple[str, ...] | list[str],
|
|
114
|
+
*,
|
|
115
|
+
context_prefix: str = "",
|
|
116
|
+
) -> str:
|
|
117
|
+
"""按字段顺序拼出一行状态栏。
|
|
118
|
+
|
|
119
|
+
:param context_prefix: 加在 ``context-used`` 前面的前缀。REPL 与 TUI 用
|
|
120
|
+
``"上下文 "`` 保留原有措辞,单独渲染这个字段时保持空串。
|
|
121
|
+
"""
|
|
122
|
+
rendered = [
|
|
123
|
+
text
|
|
124
|
+
for key in fields
|
|
125
|
+
if (text := _render_field(values, key, context_prefix=context_prefix))
|
|
126
|
+
]
|
|
127
|
+
return " · ".join(rendered)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _render_field(values: StatusLineValues, key: str, *, context_prefix: str) -> str:
|
|
131
|
+
match key:
|
|
132
|
+
case "model":
|
|
133
|
+
return values.model
|
|
134
|
+
case "context-used":
|
|
135
|
+
return f"{context_prefix}{values.context_percent:.1f}%"
|
|
136
|
+
case "cost":
|
|
137
|
+
return f"${values.cost:.4f}"
|
|
138
|
+
case "tools":
|
|
139
|
+
return f"工具 {values.tool_count}"
|
|
140
|
+
case "permission":
|
|
141
|
+
return f"权限 {values.permission}" if values.permission else ""
|
|
142
|
+
case "plan":
|
|
143
|
+
return values.plan
|
|
144
|
+
case "background":
|
|
145
|
+
return f"后台 {values.background}" if values.background else ""
|
|
146
|
+
case "used-tokens":
|
|
147
|
+
if values.used_tokens is None:
|
|
148
|
+
return ""
|
|
149
|
+
return f"已用 {format_token_count(values.used_tokens)}"
|
|
150
|
+
case "context-remaining":
|
|
151
|
+
if values.context_remaining is None:
|
|
152
|
+
return ""
|
|
153
|
+
return f"剩余 {format_token_count(values.context_remaining)}"
|
|
154
|
+
case "context-window":
|
|
155
|
+
if values.context_window is None:
|
|
156
|
+
return ""
|
|
157
|
+
return f"窗口 {format_token_count(values.context_window)}"
|
|
158
|
+
case "cache-hit":
|
|
159
|
+
if values.cache_hit is None:
|
|
160
|
+
return ""
|
|
161
|
+
return f"缓存 {values.cache_hit:.1%}"
|
|
162
|
+
case _:
|
|
163
|
+
raise ValueError(f"未知的状态栏字段:{key}")
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""子代理与工作树(S40)。
|
|
2
|
+
|
|
3
|
+
一个子代理是一次**独立的 AgentSession**:独立的会话文件、独立的转录、独立的
|
|
4
|
+
工具集合、独立的权限引擎与独立的用量账单。父会话只拿到一条 ``task`` 工具结果,
|
|
5
|
+
内容是摘要、关键文件路径与(后台任务时)工作树 diff。
|
|
6
|
+
|
|
7
|
+
模块按职责拆开,导入时全部走具体子模块,避免 ``tools`` 包与 ``session`` 包之间的
|
|
8
|
+
循环依赖:
|
|
9
|
+
|
|
10
|
+
| 模块 | 职责 |
|
|
11
|
+
|---|---|
|
|
12
|
+
| :mod:`.settings` | 运行参数与一份代理定义 |
|
|
13
|
+
| :mod:`.contract` | ``task`` 工具的名字、schema 与提示词常量 |
|
|
14
|
+
| :mod:`.definitions` | 内置代理 + 全局 / 项目目录里的定义文件 |
|
|
15
|
+
| :mod:`.registry` | 任务登记表、并发上限与后台任务收尾 |
|
|
16
|
+
| :mod:`.worktree` | 后台任务的 Git 工作树与 diff |
|
|
17
|
+
| :mod:`.runtime` | 装配、执行、取消、超时与结果回传 |
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
__all__: list[str] = []
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""``task`` 工具的协议面:名字、JSON Schema 与提示词常量。
|
|
2
|
+
|
|
3
|
+
单独成模块是为了切断循环导入:``tools/__init__.py`` 要把 ``task`` 登记进内建工具名
|
|
4
|
+
与提示词表,而 ``runtime.py`` 反过来要用 ``braid_agent.tools`` 的工具类型。这里只放
|
|
5
|
+
纯数据,不导入任何 ``braid_coding_agent`` 模块。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from braid_ai.types import JsonValue
|
|
11
|
+
|
|
12
|
+
TASK_TOOL_NAME = "task"
|
|
13
|
+
|
|
14
|
+
TASK_PARAMETERS: dict[str, JsonValue] = {
|
|
15
|
+
"type": "object",
|
|
16
|
+
"properties": {
|
|
17
|
+
"agent": {
|
|
18
|
+
"type": "string",
|
|
19
|
+
"description": (
|
|
20
|
+
"Name of a registered subagent. Use /agents in the REPL to list them. "
|
|
21
|
+
"Built-in: explore (read-only search) and general (can edit files)."
|
|
22
|
+
),
|
|
23
|
+
},
|
|
24
|
+
"prompt": {
|
|
25
|
+
"type": "string",
|
|
26
|
+
"description": (
|
|
27
|
+
"The complete task for the subagent. It starts a fresh conversation and "
|
|
28
|
+
"cannot see the parent transcript, so include every path, constraint and "
|
|
29
|
+
"expected output shape here."
|
|
30
|
+
),
|
|
31
|
+
},
|
|
32
|
+
"run_in_background": {
|
|
33
|
+
"type": "boolean",
|
|
34
|
+
"description": (
|
|
35
|
+
"Run in an isolated Git worktree while the parent keeps working. The result "
|
|
36
|
+
"is delivered when the parent run ends. Requires a Git repository with a commit."
|
|
37
|
+
),
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
"required": ["agent", "prompt"],
|
|
41
|
+
"additionalProperties": False,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
TASK_DESCRIPTION = (
|
|
45
|
+
"Delegate a self-contained task to an independent subagent. The subagent has its own "
|
|
46
|
+
"conversation file, tool set, permission mode and usage bill; its tool calls and file "
|
|
47
|
+
"contents never enter the parent transcript. You receive one tool result containing the "
|
|
48
|
+
"summary, key file paths and (for background tasks) a Git worktree diff. "
|
|
49
|
+
"Registered agents: {agents}. A failed subagent returns an error result; report it and "
|
|
50
|
+
"continue. Synchronous by default; use run_in_background only for independent work that "
|
|
51
|
+
"should not block this turn."
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
TASK_PROMPT_SNIPPET = "Delegate a self-contained task to an independent subagent"
|
|
55
|
+
|
|
56
|
+
TASK_PROMPT_GUIDELINES: tuple[str, ...] = (
|
|
57
|
+
"For broad exploration, reading many files, or independent work that would otherwise "
|
|
58
|
+
"fill this conversation, call task with a self-contained prompt: the subagent cannot see "
|
|
59
|
+
"anything you have discussed here",
|
|
60
|
+
"A task result is one summary with key file paths and the subagent's own usage; do not "
|
|
61
|
+
"paste the subagent's transcript into this conversation, and read a file again here only "
|
|
62
|
+
"when you truly need its full contents",
|
|
63
|
+
"Set run_in_background to true only when the task is independent and can be isolated in a "
|
|
64
|
+
"Git worktree; its diff is delivered when this run ends and the main worktree stays clean",
|
|
65
|
+
"When task returns an error result, state the failure and continue with other tools "
|
|
66
|
+
"instead of retrying the same call repeatedly",
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
__all__ = [
|
|
70
|
+
"TASK_DESCRIPTION",
|
|
71
|
+
"TASK_PARAMETERS",
|
|
72
|
+
"TASK_PROMPT_GUIDELINES",
|
|
73
|
+
"TASK_PROMPT_SNIPPET",
|
|
74
|
+
"TASK_TOOL_NAME",
|
|
75
|
+
]
|