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,610 @@
|
|
|
1
|
+
"""子代理运行时:装配、执行、隔离、取消与结果回传。
|
|
2
|
+
|
|
3
|
+
一次 ``task`` 调用走两种形状:
|
|
4
|
+
|
|
5
|
+
- **同步**:在工具调用里等子代理跑完,``AgentToolResult`` 直接带摘要、关键路径、
|
|
6
|
+
独立用量与会话文件路径。父会话只多一条工具结果。
|
|
7
|
+
- **后台**:先建 Git 工作树、登记任务、立刻返回任务号;子代理在独立工作树里跑,
|
|
8
|
+
收尾时由父会话的 ``agent_end`` 订阅者等齐全部后台任务,把结果以 ``follow_up``
|
|
9
|
+
注入父会话。会话层 ``_handle_post_agent_run()`` 看到队列里有消息就会续跑一次,
|
|
10
|
+
主代理因此能在同一次 ``prompt()`` 里汇总 diff,而不是等用户再敲一句话。
|
|
11
|
+
|
|
12
|
+
等齐的点选在 ``agent_end`` 而不是"每个任务完成就注入":后者会让同一批结果分几次
|
|
13
|
+
进入转录,模型看到的顺序取决于网络快慢,测试也无法复现。
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import os
|
|
20
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink
|
|
25
|
+
from braid_agent.types import ToolExecutionStartEvent
|
|
26
|
+
from braid_ai.cancel import CancelToken
|
|
27
|
+
from braid_ai.types import AssistantMessage, JsonValue, TextContent
|
|
28
|
+
from braid_ai.utils.clock import Clock, SystemClock
|
|
29
|
+
from braid_coding_agent.checkpoint import GitError, GitWorkspaceError
|
|
30
|
+
from braid_coding_agent.permissions.model import PermissionMode
|
|
31
|
+
from braid_coding_agent.session.agent_session import (
|
|
32
|
+
AgentEndWithRetryEvent,
|
|
33
|
+
AgentSession,
|
|
34
|
+
SessionEvent,
|
|
35
|
+
)
|
|
36
|
+
from braid_coding_agent.session.manager import SessionManager
|
|
37
|
+
from braid_coding_agent.subagents.contract import (
|
|
38
|
+
TASK_DESCRIPTION,
|
|
39
|
+
TASK_PARAMETERS,
|
|
40
|
+
TASK_TOOL_NAME,
|
|
41
|
+
)
|
|
42
|
+
from braid_coding_agent.subagents.definitions import (
|
|
43
|
+
DefinitionDiagnostic,
|
|
44
|
+
DefinitionScan,
|
|
45
|
+
definition_by_name,
|
|
46
|
+
load_definitions,
|
|
47
|
+
)
|
|
48
|
+
from braid_coding_agent.subagents.registry import (
|
|
49
|
+
SubagentLimitError,
|
|
50
|
+
SubagentRegistry,
|
|
51
|
+
SubagentTask,
|
|
52
|
+
)
|
|
53
|
+
from braid_coding_agent.subagents.settings import SubagentSettings, SubagentSpec
|
|
54
|
+
from braid_coding_agent.subagents.worktree import (
|
|
55
|
+
WorktreeHandle,
|
|
56
|
+
collect_diff,
|
|
57
|
+
create_worktree,
|
|
58
|
+
)
|
|
59
|
+
from braid_coding_agent.tools.args import optional_bool_arg, string_arg
|
|
60
|
+
|
|
61
|
+
#: 摘要与结果文本的上限。子代理的完整回答留在它自己的会话文件里。
|
|
62
|
+
SUMMARY_LIMIT = 4000
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(slots=True, frozen=True)
|
|
66
|
+
class SpawnRequest:
|
|
67
|
+
"""交给会话装配闭包的一次派生请求。
|
|
68
|
+
|
|
69
|
+
``permission_mode`` 是派生的那一刻父会话**正在使用**的权限模式。装配层按它
|
|
70
|
+
与子代理定义里的模式取更严的一个:父会话在运行中进了规划模式或改成只读时,
|
|
71
|
+
子代理不能还按启动配置里的宽松模式跑。
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
task_id: str
|
|
75
|
+
spec: SubagentSpec
|
|
76
|
+
cwd: str
|
|
77
|
+
depth: int
|
|
78
|
+
session_dir: str
|
|
79
|
+
parent_session_file: str | None
|
|
80
|
+
permission_mode: PermissionMode | None = None
|
|
81
|
+
#: 后台会话分离时传入已经克隆好的会话树;``None`` 表示新建一份空会话。
|
|
82
|
+
fork: SessionManager | None = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
type SpawnFactory = Callable[[SpawnRequest], AgentSession]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(slots=True)
|
|
89
|
+
class SubagentOwner:
|
|
90
|
+
"""持有 ``task`` 工具的那一个会话。``session`` 在装配完成后填入。"""
|
|
91
|
+
|
|
92
|
+
runtime: SubagentRuntime
|
|
93
|
+
depth: int
|
|
94
|
+
session: AgentSession | None = None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _error_result(text: str, *, details: JsonValue = None) -> AgentToolResult:
|
|
98
|
+
return AgentToolResult(content=[TextContent(text=text)], details=details, is_error=True)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _final_text(child: AgentSession | None) -> str:
|
|
102
|
+
"""子代理最后一条助手消息的文本。父会话只需要这一段结论。"""
|
|
103
|
+
if child is None:
|
|
104
|
+
return ""
|
|
105
|
+
for message in reversed(child.agent.state.messages):
|
|
106
|
+
if not isinstance(message, AssistantMessage):
|
|
107
|
+
continue
|
|
108
|
+
parts = [block.text for block in message.content if isinstance(block, TextContent)]
|
|
109
|
+
if parts:
|
|
110
|
+
return "\n".join(parts)[:SUMMARY_LIMIT]
|
|
111
|
+
return ""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _collect_paths(event: SessionEvent, paths: list[str]) -> None:
|
|
115
|
+
"""从工具调用参数里收集关键文件路径;结果文本与文件清单都靠它。"""
|
|
116
|
+
if isinstance(event, ToolExecutionStartEvent):
|
|
117
|
+
candidate = event.args.get("path")
|
|
118
|
+
if isinstance(candidate, str) and candidate.strip():
|
|
119
|
+
paths.append(candidate.strip())
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class SubagentRuntime:
|
|
123
|
+
"""进程级运行时。一个进程一份,多个父会话各自通过 :meth:`bind` 接进来。"""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
*,
|
|
128
|
+
settings: SubagentSettings,
|
|
129
|
+
specs: Sequence[SubagentSpec],
|
|
130
|
+
spawn: SpawnFactory,
|
|
131
|
+
worktree_root: str,
|
|
132
|
+
parent_cwd: str,
|
|
133
|
+
session_root: str | None = None,
|
|
134
|
+
agent_dir: str | None = None,
|
|
135
|
+
known_tools: Sequence[str] = (),
|
|
136
|
+
definition_diagnostics: Sequence[DefinitionDiagnostic] = (),
|
|
137
|
+
clock: Clock | None = None,
|
|
138
|
+
) -> None:
|
|
139
|
+
self._settings = settings
|
|
140
|
+
self._specs = tuple(specs)
|
|
141
|
+
self._spawn = spawn
|
|
142
|
+
self._worktree_root = os.path.abspath(worktree_root)
|
|
143
|
+
self._parent_cwd = os.path.abspath(parent_cwd)
|
|
144
|
+
self._session_root = os.path.abspath(
|
|
145
|
+
session_root
|
|
146
|
+
if session_root is not None
|
|
147
|
+
else os.path.join(os.path.dirname(self._worktree_root), "subagents")
|
|
148
|
+
)
|
|
149
|
+
self._clock: Clock = clock if clock is not None else SystemClock()
|
|
150
|
+
self._agent_dir = None if agent_dir is None else os.path.abspath(agent_dir)
|
|
151
|
+
self._known_tools = tuple(known_tools)
|
|
152
|
+
self._diagnostics = tuple(definition_diagnostics)
|
|
153
|
+
self._registry = SubagentRegistry(
|
|
154
|
+
max_background=settings.max_background,
|
|
155
|
+
max_concurrent=settings.max_concurrent,
|
|
156
|
+
)
|
|
157
|
+
self._notified: set[str] = set()
|
|
158
|
+
#: 运行中的子会话。``/tasks send`` 通过这些引用把消息投给子代理。
|
|
159
|
+
self._children: dict[str, AgentSession] = {}
|
|
160
|
+
|
|
161
|
+
# ---------------------------------------------------------------- 只读
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def registry(self) -> SubagentRegistry:
|
|
165
|
+
return self._registry
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def settings(self) -> SubagentSettings:
|
|
169
|
+
return self._settings
|
|
170
|
+
|
|
171
|
+
def specs(self) -> tuple[SubagentSpec, ...]:
|
|
172
|
+
return self._specs
|
|
173
|
+
|
|
174
|
+
def lookup(self, name: str) -> SubagentSpec | None:
|
|
175
|
+
return definition_by_name(self._specs, name)
|
|
176
|
+
|
|
177
|
+
def agents_wire(self) -> list[dict[str, JsonValue]]:
|
|
178
|
+
return [spec.wire() for spec in self._specs]
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def definition_diagnostics(self) -> tuple[DefinitionDiagnostic, ...]:
|
|
182
|
+
return self._diagnostics
|
|
183
|
+
|
|
184
|
+
def diagnostics_wire(self) -> list[dict[str, JsonValue]]:
|
|
185
|
+
return [issue.wire() for issue in self._diagnostics]
|
|
186
|
+
|
|
187
|
+
def settings_wire(self) -> dict[str, JsonValue]:
|
|
188
|
+
return self._settings.wire()
|
|
189
|
+
|
|
190
|
+
def tasks_wire(self) -> list[dict[str, JsonValue]]:
|
|
191
|
+
return [task.wire() for task in self._registry.tasks()]
|
|
192
|
+
|
|
193
|
+
def reload(self) -> DefinitionScan:
|
|
194
|
+
"""重新扫描定义目录。运行中的任务不受影响,后续派生使用新定义。"""
|
|
195
|
+
if self._agent_dir is None:
|
|
196
|
+
raise RuntimeError("这次运行没有记录配置目录,无法重新扫描子代理定义")
|
|
197
|
+
scan = load_definitions(
|
|
198
|
+
agent_dir=Path(self._agent_dir),
|
|
199
|
+
cwd=self._parent_cwd,
|
|
200
|
+
known_tools=self._known_tools,
|
|
201
|
+
)
|
|
202
|
+
self._specs = scan.specs
|
|
203
|
+
self._diagnostics = scan.diagnostics
|
|
204
|
+
return scan
|
|
205
|
+
|
|
206
|
+
async def send(self, task_id: str, text: str) -> str:
|
|
207
|
+
"""给运行中的子代理追加一条消息。父代理与子代理之间的唯一通信入口。"""
|
|
208
|
+
task = self._registry.get(task_id)
|
|
209
|
+
if task is None:
|
|
210
|
+
return f"没有任务 {task_id}"
|
|
211
|
+
if task.status != "running":
|
|
212
|
+
return f"任务 {task_id} 状态是 {task.status},不能再发送消息"
|
|
213
|
+
child = self._children.get(task_id)
|
|
214
|
+
if child is None:
|
|
215
|
+
return f"任务 {task_id} 没有可写的子会话(同步任务只能在当前回合内完成)"
|
|
216
|
+
if not text.strip():
|
|
217
|
+
return "消息不能为空"
|
|
218
|
+
await child.follow_up(text)
|
|
219
|
+
return f"消息已排队给任务 {task_id},子代理下一次停下时会读到"
|
|
220
|
+
|
|
221
|
+
def cancel(self, task_id: str) -> str:
|
|
222
|
+
"""取消一个运行中的后台任务;同步任务没有独立句柄,不能从这里停。"""
|
|
223
|
+
task = self._registry.get(task_id)
|
|
224
|
+
if task is None:
|
|
225
|
+
return f"没有任务 {task_id}"
|
|
226
|
+
if task.status != "running":
|
|
227
|
+
return f"任务 {task_id} 状态是 {task.status},不需要取消"
|
|
228
|
+
handle = self._registry.handle(task_id)
|
|
229
|
+
if handle is None:
|
|
230
|
+
return f"任务 {task_id} 是同步任务,取消请直接中断当前回合"
|
|
231
|
+
handle.cancel()
|
|
232
|
+
self._registry.finish(
|
|
233
|
+
task_id,
|
|
234
|
+
status="cancelled",
|
|
235
|
+
error="用户通过 /tasks cancel 取消",
|
|
236
|
+
finished_ms=self._clock.monotonic_ms(),
|
|
237
|
+
)
|
|
238
|
+
return f"已取消任务 {task_id}"
|
|
239
|
+
|
|
240
|
+
def clear_finished(self) -> tuple[str, ...]:
|
|
241
|
+
removed = self._registry.clear_finished()
|
|
242
|
+
for task_id in removed:
|
|
243
|
+
self._notified.discard(task_id)
|
|
244
|
+
return removed
|
|
245
|
+
|
|
246
|
+
# ------------------------------------------------------------ 装配接线
|
|
247
|
+
|
|
248
|
+
def new_owner(self, depth: int) -> SubagentOwner:
|
|
249
|
+
return SubagentOwner(runtime=self, depth=depth)
|
|
250
|
+
|
|
251
|
+
def bind(self, owner: SubagentOwner) -> None:
|
|
252
|
+
"""只把第 0 层会话接成后台结果的汇合点。会话 ``dispose`` 时会清掉监听器。
|
|
253
|
+
|
|
254
|
+
子会话不订阅:它的 ``agent_end`` 若也去 ``wait_all()``,就会等到正在跑它的
|
|
255
|
+
那个后台任务自己,形成自等待。所有后台结果统一在顶层父会话的
|
|
256
|
+
``agent_end`` 汇合,嵌套派生出来的任务也一样。
|
|
257
|
+
"""
|
|
258
|
+
if owner.depth > 0:
|
|
259
|
+
return
|
|
260
|
+
session = owner.session
|
|
261
|
+
if session is None:
|
|
262
|
+
raise RuntimeError("子代理运行时绑定的会话还没有构造完成")
|
|
263
|
+
|
|
264
|
+
async def listener(event: SessionEvent) -> None:
|
|
265
|
+
await self._on_parent_event(owner, event)
|
|
266
|
+
|
|
267
|
+
session.subscribe(listener)
|
|
268
|
+
|
|
269
|
+
def make_task_tool(self, owner: SubagentOwner) -> AgentTool:
|
|
270
|
+
"""造 ``task`` 工具。``owner`` 是持有它的那一个会话,不是全局当前会话。"""
|
|
271
|
+
names = "; ".join(f"{spec.name}: {spec.description}" for spec in self._specs)
|
|
272
|
+
description = TASK_DESCRIPTION.format(agents=names)
|
|
273
|
+
|
|
274
|
+
async def execute(
|
|
275
|
+
tool_call_id: str,
|
|
276
|
+
args: dict[str, JsonValue],
|
|
277
|
+
signal: CancelToken | None,
|
|
278
|
+
on_update: ToolUpdateSink,
|
|
279
|
+
) -> AgentToolResult:
|
|
280
|
+
del tool_call_id, on_update
|
|
281
|
+
return await self.execute(
|
|
282
|
+
agent=string_arg(args, "agent"),
|
|
283
|
+
prompt=string_arg(args, "prompt"),
|
|
284
|
+
background=optional_bool_arg(args, "run_in_background") or False,
|
|
285
|
+
owner=owner,
|
|
286
|
+
signal=signal,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
return AgentTool(
|
|
290
|
+
name=TASK_TOOL_NAME,
|
|
291
|
+
label=TASK_TOOL_NAME,
|
|
292
|
+
description=description,
|
|
293
|
+
parameters=TASK_PARAMETERS,
|
|
294
|
+
execute=execute,
|
|
295
|
+
# 子代理自己有整轮预算(``timeout_seconds``)。循环的硬停止点晚于它,
|
|
296
|
+
# 只在子会话没有按自己的预算收尾时兜底——一条跑不完的子任务不该拖住父会话。
|
|
297
|
+
default_timeout_s=self._settings.timeout_seconds,
|
|
298
|
+
max_timeout_s=self._settings.timeout_seconds,
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
# ---------------------------------------------------------------- 执行
|
|
302
|
+
|
|
303
|
+
async def execute(
|
|
304
|
+
self,
|
|
305
|
+
*,
|
|
306
|
+
agent: str,
|
|
307
|
+
prompt: str,
|
|
308
|
+
background: bool,
|
|
309
|
+
owner: SubagentOwner,
|
|
310
|
+
signal: CancelToken | None = None,
|
|
311
|
+
) -> AgentToolResult:
|
|
312
|
+
"""校验 → 登记 → 同步执行或派出后台任务。所有可预期失败都变成 is_error。"""
|
|
313
|
+
if owner.depth >= self._settings.max_depth:
|
|
314
|
+
return _error_result(
|
|
315
|
+
f"子代理嵌套深度已达上限 {self._settings.max_depth}:当前在第 "
|
|
316
|
+
f"{owner.depth} 层。子代理不能再派生子代理。"
|
|
317
|
+
)
|
|
318
|
+
spec = self.lookup(agent)
|
|
319
|
+
if spec is None:
|
|
320
|
+
names = ", ".join(item.name for item in self._specs)
|
|
321
|
+
return _error_result(f"未知子代理 {agent!r};可用:{names}。用 /agents 查看定义。")
|
|
322
|
+
if not prompt.strip():
|
|
323
|
+
return _error_result("prompt 不能为空:子代理看不到父会话,任务必须自包含")
|
|
324
|
+
if signal is not None and signal.cancelled:
|
|
325
|
+
return _error_result(
|
|
326
|
+
f"Operation aborted({signal.reason or '运行已取消'}):不再启动新的子代理"
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
parent = owner.session
|
|
330
|
+
parent_file = parent.session.get_session_file() if parent is not None else None
|
|
331
|
+
parent_engine = parent.permission_engine if parent is not None else None
|
|
332
|
+
parent_mode = parent_engine.settings.mode if parent_engine is not None else None
|
|
333
|
+
try:
|
|
334
|
+
task = self._registry.create(
|
|
335
|
+
agent=agent,
|
|
336
|
+
prompt=prompt,
|
|
337
|
+
background=background,
|
|
338
|
+
depth=owner.depth + 1,
|
|
339
|
+
cwd=self._parent_cwd,
|
|
340
|
+
started_ms=self._clock.monotonic_ms(),
|
|
341
|
+
)
|
|
342
|
+
except SubagentLimitError as exc:
|
|
343
|
+
# 超限立刻失败,不排队:模型要知道"上限是多少"才能改写计划,排队只会让
|
|
344
|
+
# 它以为调用还在跑。
|
|
345
|
+
return _error_result(f"本次没有启动子代理。{exc}")
|
|
346
|
+
except Exception as exc:
|
|
347
|
+
return _error_result(f"无法登记子代理任务:{type(exc).__name__}: {exc}")
|
|
348
|
+
|
|
349
|
+
if background:
|
|
350
|
+
handle: WorktreeHandle | None = None
|
|
351
|
+
if spec.isolation == "none":
|
|
352
|
+
task.cwd = self._parent_cwd
|
|
353
|
+
location = f"共享工作目录 {self._parent_cwd}"
|
|
354
|
+
else:
|
|
355
|
+
try:
|
|
356
|
+
handle = await create_worktree(
|
|
357
|
+
cwd=self._parent_cwd, root=self._worktree_root, task_id=task.id
|
|
358
|
+
)
|
|
359
|
+
except (GitError, GitWorkspaceError, OSError) as exc:
|
|
360
|
+
message = f"{type(exc).__name__}: {exc}"
|
|
361
|
+
self._registry.finish(
|
|
362
|
+
task.id,
|
|
363
|
+
status="failed",
|
|
364
|
+
error=message,
|
|
365
|
+
finished_ms=self._clock.monotonic_ms(),
|
|
366
|
+
)
|
|
367
|
+
return _error_result(
|
|
368
|
+
f"后台子代理 {task.id} 启动失败:{message}。"
|
|
369
|
+
"后台任务要求当前目录是至少有一次提交的 Git 仓库;"
|
|
370
|
+
"可以改用同步任务、把 isolation 设为 none,或在别处初始化仓库。",
|
|
371
|
+
details=task.wire(),
|
|
372
|
+
)
|
|
373
|
+
task.cwd = handle.path
|
|
374
|
+
task.worktree = handle.path
|
|
375
|
+
task.branch = handle.branch
|
|
376
|
+
location = f"工作树 {handle.path}"
|
|
377
|
+
runner = asyncio.create_task(
|
|
378
|
+
self._background(task, spec, prompt, handle, parent_file, parent_mode)
|
|
379
|
+
)
|
|
380
|
+
self._registry.attach(task.id, runner)
|
|
381
|
+
return AgentToolResult(
|
|
382
|
+
content=[
|
|
383
|
+
TextContent(
|
|
384
|
+
text=(
|
|
385
|
+
f"后台子代理 {task.id}({agent})已启动,{location}。"
|
|
386
|
+
"结果会在本次运行结束时以一条通知回到主会话;"
|
|
387
|
+
"用 /tasks 查看状态,/agents 查看定义。"
|
|
388
|
+
)
|
|
389
|
+
)
|
|
390
|
+
],
|
|
391
|
+
details=task.wire(),
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
await self._execute_task(task, spec, prompt, signal, None, parent_file, parent_mode)
|
|
395
|
+
if task.status != "completed":
|
|
396
|
+
return _error_result(task.result_text(), details=task.wire())
|
|
397
|
+
return AgentToolResult(content=[TextContent(text=task.result_text())], details=task.wire())
|
|
398
|
+
|
|
399
|
+
async def start_detached(
|
|
400
|
+
self,
|
|
401
|
+
*,
|
|
402
|
+
session: AgentSession,
|
|
403
|
+
prompt: str,
|
|
404
|
+
spec_name: str = "background",
|
|
405
|
+
notify: Callable[[SubagentTask], Awaitable[None]] | None = None,
|
|
406
|
+
) -> SubagentTask:
|
|
407
|
+
"""把当前会话克隆成一份后台 Agent,并立刻返回任务记录。
|
|
408
|
+
|
|
409
|
+
克隆发生在会话管理层:新会话文件包含当前活动分支的全部条目,头里的
|
|
410
|
+
``parentSession`` 指回原文件。子代理看到的是同一段对话,后续写入只落在新文件。
|
|
411
|
+
工作目录与父会话共享;后台任务的交付物是摘要与子会话文件。
|
|
412
|
+
|
|
413
|
+
``notify`` 在任务收尾后调用一次,用来把结果送回原会话。分离任务的句柄不参与
|
|
414
|
+
``wait_all``:它不属于任何一次回合的收尾,父会话结束一回合时不该等它。
|
|
415
|
+
"""
|
|
416
|
+
spec = self.lookup(spec_name)
|
|
417
|
+
if spec is None:
|
|
418
|
+
raise ValueError(f"没有名为 {spec_name!r} 的子代理定义")
|
|
419
|
+
if not prompt.strip():
|
|
420
|
+
raise ValueError("后台会话需要一个非空任务")
|
|
421
|
+
clone = session.session.clone()
|
|
422
|
+
parent_file = session.session.get_session_file()
|
|
423
|
+
parent_engine = session.permission_engine
|
|
424
|
+
parent_mode = parent_engine.settings.mode if parent_engine is not None else None
|
|
425
|
+
task = self._registry.create(
|
|
426
|
+
agent=spec.name,
|
|
427
|
+
prompt=prompt,
|
|
428
|
+
background=True,
|
|
429
|
+
depth=1,
|
|
430
|
+
cwd=self._parent_cwd,
|
|
431
|
+
started_ms=self._clock.monotonic_ms(),
|
|
432
|
+
)
|
|
433
|
+
runner = asyncio.create_task(
|
|
434
|
+
self._run_detached(
|
|
435
|
+
task,
|
|
436
|
+
spec,
|
|
437
|
+
prompt,
|
|
438
|
+
clone,
|
|
439
|
+
parent_file,
|
|
440
|
+
parent_mode,
|
|
441
|
+
notify,
|
|
442
|
+
)
|
|
443
|
+
)
|
|
444
|
+
self._registry.attach(task.id, runner, detached=True)
|
|
445
|
+
return task
|
|
446
|
+
|
|
447
|
+
async def _run_detached(
|
|
448
|
+
self,
|
|
449
|
+
task: SubagentTask,
|
|
450
|
+
spec: SubagentSpec,
|
|
451
|
+
prompt: str,
|
|
452
|
+
clone: SessionManager,
|
|
453
|
+
parent_file: str | None,
|
|
454
|
+
parent_mode: PermissionMode | None,
|
|
455
|
+
notify: Callable[[SubagentTask], Awaitable[None]] | None,
|
|
456
|
+
) -> None:
|
|
457
|
+
await self._execute_task(
|
|
458
|
+
task,
|
|
459
|
+
spec,
|
|
460
|
+
prompt,
|
|
461
|
+
None,
|
|
462
|
+
None,
|
|
463
|
+
parent_file,
|
|
464
|
+
parent_mode,
|
|
465
|
+
fork=clone,
|
|
466
|
+
)
|
|
467
|
+
# 结果已经直接交给原会话,``agent_end`` 汇合时不能再注入一次。
|
|
468
|
+
self._notified.add(task.id)
|
|
469
|
+
if notify is not None:
|
|
470
|
+
await notify(task)
|
|
471
|
+
|
|
472
|
+
async def _background(
|
|
473
|
+
self,
|
|
474
|
+
task: SubagentTask,
|
|
475
|
+
spec: SubagentSpec,
|
|
476
|
+
prompt: str,
|
|
477
|
+
handle: WorktreeHandle | None,
|
|
478
|
+
parent_file: str | None,
|
|
479
|
+
parent_mode: PermissionMode | None,
|
|
480
|
+
) -> None:
|
|
481
|
+
await self._execute_task(task, spec, prompt, None, handle, parent_file, parent_mode)
|
|
482
|
+
|
|
483
|
+
async def _execute_task(
|
|
484
|
+
self,
|
|
485
|
+
task: SubagentTask,
|
|
486
|
+
spec: SubagentSpec,
|
|
487
|
+
prompt: str,
|
|
488
|
+
signal: CancelToken | None,
|
|
489
|
+
handle: WorktreeHandle | None,
|
|
490
|
+
parent_file: str | None,
|
|
491
|
+
parent_mode: PermissionMode | None,
|
|
492
|
+
*,
|
|
493
|
+
fork: SessionManager | None = None,
|
|
494
|
+
) -> None:
|
|
495
|
+
"""跑一个子代理并把结果写进登记记录。异常一律变成 failed 状态。"""
|
|
496
|
+
child: AgentSession | None = None
|
|
497
|
+
watcher: asyncio.Task[None] | None = None
|
|
498
|
+
paths: list[str] = []
|
|
499
|
+
unsubscribe: Callable[[], None] | None = None
|
|
500
|
+
try:
|
|
501
|
+
child = self._spawn(
|
|
502
|
+
SpawnRequest(
|
|
503
|
+
task_id=task.id,
|
|
504
|
+
spec=spec,
|
|
505
|
+
cwd=task.cwd,
|
|
506
|
+
depth=task.depth,
|
|
507
|
+
session_dir=os.path.join(self._session_root, task.id),
|
|
508
|
+
parent_session_file=parent_file,
|
|
509
|
+
permission_mode=parent_mode,
|
|
510
|
+
fork=fork,
|
|
511
|
+
)
|
|
512
|
+
)
|
|
513
|
+
task.session_file = child.session.get_session_file()
|
|
514
|
+
self._children[task.id] = child
|
|
515
|
+
unsubscribe = child.subscribe(lambda event: _collect_paths(event, paths))
|
|
516
|
+
if signal is not None:
|
|
517
|
+
watcher = asyncio.create_task(self._watch_cancel(child, signal))
|
|
518
|
+
await asyncio.wait_for(child.prompt(prompt), timeout=self._settings.timeout_seconds)
|
|
519
|
+
usage = {
|
|
520
|
+
"input": child.usage.input,
|
|
521
|
+
"output": child.usage.output,
|
|
522
|
+
"totalTokens": child.usage.total_tokens,
|
|
523
|
+
}
|
|
524
|
+
files = tuple(dict.fromkeys(paths))
|
|
525
|
+
diff = ""
|
|
526
|
+
if handle is not None:
|
|
527
|
+
diff, work_files = await collect_diff(handle)
|
|
528
|
+
files = tuple(dict.fromkeys([*files, *work_files]))
|
|
529
|
+
self._registry.finish(
|
|
530
|
+
task.id,
|
|
531
|
+
status="completed",
|
|
532
|
+
summary=_final_text(child),
|
|
533
|
+
files=files,
|
|
534
|
+
diff=diff,
|
|
535
|
+
usage=usage,
|
|
536
|
+
cost_usd=child.usage.cost.total,
|
|
537
|
+
finished_ms=self._clock.monotonic_ms(),
|
|
538
|
+
)
|
|
539
|
+
except asyncio.CancelledError:
|
|
540
|
+
if task.status == "running":
|
|
541
|
+
self._registry.finish(
|
|
542
|
+
task.id,
|
|
543
|
+
status="cancelled",
|
|
544
|
+
error="父会话收尾,子代理被取消",
|
|
545
|
+
summary=_final_text(child),
|
|
546
|
+
finished_ms=self._clock.monotonic_ms(),
|
|
547
|
+
)
|
|
548
|
+
else:
|
|
549
|
+
task.summary = _final_text(child) or task.summary
|
|
550
|
+
raise
|
|
551
|
+
except Exception as exc:
|
|
552
|
+
self._registry.finish(
|
|
553
|
+
task.id,
|
|
554
|
+
status="failed",
|
|
555
|
+
error=f"{type(exc).__name__}: {exc}",
|
|
556
|
+
summary=_final_text(child),
|
|
557
|
+
finished_ms=self._clock.monotonic_ms(),
|
|
558
|
+
)
|
|
559
|
+
finally:
|
|
560
|
+
self._children.pop(task.id, None)
|
|
561
|
+
if unsubscribe is not None:
|
|
562
|
+
unsubscribe()
|
|
563
|
+
if watcher is not None:
|
|
564
|
+
watcher.cancel()
|
|
565
|
+
await asyncio.gather(watcher, return_exceptions=True)
|
|
566
|
+
if child is not None:
|
|
567
|
+
await child.dispose()
|
|
568
|
+
|
|
569
|
+
@staticmethod
|
|
570
|
+
async def _watch_cancel(child: AgentSession, signal: CancelToken) -> None:
|
|
571
|
+
"""父 run 被取消时把取消传给子会话,让它写下 ``aborted`` 消息。"""
|
|
572
|
+
while not signal.cancelled:
|
|
573
|
+
await asyncio.sleep(0.05)
|
|
574
|
+
await child.abort()
|
|
575
|
+
|
|
576
|
+
# -------------------------------------------------------- 结果回传与收尾
|
|
577
|
+
|
|
578
|
+
async def _on_parent_event(self, owner: SubagentOwner, event: SessionEvent) -> None:
|
|
579
|
+
"""``agent_end`` 是后台结果与父会话的唯一汇合点。"""
|
|
580
|
+
if not isinstance(event, AgentEndWithRetryEvent) or event.will_retry:
|
|
581
|
+
return
|
|
582
|
+
await self._registry.wait_all()
|
|
583
|
+
session = owner.session
|
|
584
|
+
if session is None or session.is_disposed:
|
|
585
|
+
return
|
|
586
|
+
for task in self._registry.tasks():
|
|
587
|
+
if not task.background or task.id in self._notified:
|
|
588
|
+
continue
|
|
589
|
+
if task.status not in ("completed", "failed", "cancelled"):
|
|
590
|
+
continue
|
|
591
|
+
self._notified.add(task.id)
|
|
592
|
+
await session.follow_up(
|
|
593
|
+
f"[后台子代理结果 · {task.id} · {task.agent}]\n{task.result_text()}\n"
|
|
594
|
+
"请把上面的摘要与 diff 汇总进你的回答;不要重复派生同一个任务。"
|
|
595
|
+
)
|
|
596
|
+
|
|
597
|
+
async def wait_background(self) -> None:
|
|
598
|
+
"""进程退出前等齐后台任务,避免子会话写到一半被截断。"""
|
|
599
|
+
await self._registry.wait_all()
|
|
600
|
+
|
|
601
|
+
def cancel_background(self) -> None:
|
|
602
|
+
self._registry.cancel_all()
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
__all__ = [
|
|
606
|
+
"SpawnFactory",
|
|
607
|
+
"SpawnRequest",
|
|
608
|
+
"SubagentOwner",
|
|
609
|
+
"SubagentRuntime",
|
|
610
|
+
]
|