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.
Files changed (192) hide show
  1. braid_coding_agent/__init__.py +13 -0
  2. braid_coding_agent/assembly.py +460 -0
  3. braid_coding_agent/cancellation.py +25 -0
  4. braid_coding_agent/checkpoint/__init__.py +106 -0
  5. braid_coding_agent/checkpoint/git.py +305 -0
  6. braid_coding_agent/checkpoint/settings.py +26 -0
  7. braid_coding_agent/checkpoint/store.py +1261 -0
  8. braid_coding_agent/checkpoint/workspace.py +220 -0
  9. braid_coding_agent/cli.py +2168 -0
  10. braid_coding_agent/commands/__init__.py +50 -0
  11. braid_coding_agent/commands/auth.py +161 -0
  12. braid_coding_agent/commands/config.py +180 -0
  13. braid_coding_agent/commands/doctor.py +511 -0
  14. braid_coding_agent/commands/mcp.py +928 -0
  15. braid_coding_agent/commands/models.py +95 -0
  16. braid_coding_agent/commands/setup.py +89 -0
  17. braid_coding_agent/commands/uninstall.py +277 -0
  18. braid_coding_agent/commands/upgrade.py +381 -0
  19. braid_coding_agent/compaction/__init__.py +174 -0
  20. braid_coding_agent/compaction/prepare.py +430 -0
  21. braid_coding_agent/compaction/summarize.py +542 -0
  22. braid_coding_agent/compaction/tokens.py +204 -0
  23. braid_coding_agent/compaction/tool_results.py +196 -0
  24. braid_coding_agent/compaction/utils.py +181 -0
  25. braid_coding_agent/config.py +2776 -0
  26. braid_coding_agent/config_files.py +191 -0
  27. braid_coding_agent/credentials.py +252 -0
  28. braid_coding_agent/discovery.py +415 -0
  29. braid_coding_agent/extensions/__init__.py +77 -0
  30. braid_coding_agent/extensions/api.py +480 -0
  31. braid_coding_agent/extensions/runner.py +553 -0
  32. braid_coding_agent/formatting/__init__.py +62 -0
  33. braid_coding_agent/formatting/settings.py +87 -0
  34. braid_coding_agent/formatting/tool.py +179 -0
  35. braid_coding_agent/lsp/__init__.py +105 -0
  36. braid_coding_agent/lsp/client.py +546 -0
  37. braid_coding_agent/lsp/manager.py +187 -0
  38. braid_coding_agent/lsp/model.py +316 -0
  39. braid_coding_agent/lsp/protocol.py +105 -0
  40. braid_coding_agent/lsp/settings.py +120 -0
  41. braid_coding_agent/lsp/tool.py +429 -0
  42. braid_coding_agent/mcp/__init__.py +101 -0
  43. braid_coding_agent/mcp/cache.py +230 -0
  44. braid_coding_agent/mcp/catalog.py +108 -0
  45. braid_coding_agent/mcp/config.py +664 -0
  46. braid_coding_agent/mcp/config_store.py +142 -0
  47. braid_coding_agent/mcp/inspector.py +85 -0
  48. braid_coding_agent/mcp/panel.py +254 -0
  49. braid_coding_agent/mcp/runtime.py +1060 -0
  50. braid_coding_agent/mcp/tools.py +579 -0
  51. braid_coding_agent/mcp/trust.py +150 -0
  52. braid_coding_agent/mcp/tui_panel.py +444 -0
  53. braid_coding_agent/messages.py +152 -0
  54. braid_coding_agent/models_view.py +105 -0
  55. braid_coding_agent/modes/__init__.py +64 -0
  56. braid_coding_agent/modes/json_mode.py +480 -0
  57. braid_coding_agent/modes/lifecycle.py +217 -0
  58. braid_coding_agent/modes/print_mode.py +257 -0
  59. braid_coding_agent/modes/repl.py +2687 -0
  60. braid_coding_agent/modes/repl_commands.py +263 -0
  61. braid_coding_agent/modes/rpc.py +953 -0
  62. braid_coding_agent/modes/skill_commands.py +88 -0
  63. braid_coding_agent/modes/tui.py +2226 -0
  64. braid_coding_agent/modes/tui_control.py +90 -0
  65. braid_coding_agent/modes/tui_model.py +1043 -0
  66. braid_coding_agent/modes/tui_render.py +327 -0
  67. braid_coding_agent/modes/tui_rich.py +751 -0
  68. braid_coding_agent/modes/tui_style.py +42 -0
  69. braid_coding_agent/modes/wire.py +81 -0
  70. braid_coding_agent/netsafe.py +82 -0
  71. braid_coding_agent/network/__init__.py +20 -0
  72. braid_coding_agent/network/cache.py +77 -0
  73. braid_coding_agent/network/fetch.py +311 -0
  74. braid_coding_agent/network/html_text.py +160 -0
  75. braid_coding_agent/network/search.py +347 -0
  76. braid_coding_agent/network/settings.py +103 -0
  77. braid_coding_agent/network/urls.py +89 -0
  78. braid_coding_agent/observability/__init__.py +101 -0
  79. braid_coding_agent/observability/audit.py +124 -0
  80. braid_coding_agent/observability/collector.py +314 -0
  81. braid_coding_agent/observability/exporter.py +74 -0
  82. braid_coding_agent/observability/logging_setup.py +149 -0
  83. braid_coding_agent/observability/redaction.py +96 -0
  84. braid_coding_agent/observability/settings.py +29 -0
  85. braid_coding_agent/observability/spans.py +239 -0
  86. braid_coding_agent/permissions/__init__.py +185 -0
  87. braid_coding_agent/permissions/command.py +586 -0
  88. braid_coding_agent/permissions/engine.py +522 -0
  89. braid_coding_agent/permissions/evaluate.py +309 -0
  90. braid_coding_agent/permissions/matching.py +233 -0
  91. braid_coding_agent/permissions/model.py +278 -0
  92. braid_coding_agent/permissions/policy.py +99 -0
  93. braid_coding_agent/permissions/readonly.py +236 -0
  94. braid_coding_agent/permissions/store.py +379 -0
  95. braid_coding_agent/project_init.py +313 -0
  96. braid_coding_agent/prompt/__init__.py +98 -0
  97. braid_coding_agent/prompt/context_files.py +253 -0
  98. braid_coding_agent/prompt/project_context.py +172 -0
  99. braid_coding_agent/prompt/system_prompt.py +378 -0
  100. braid_coding_agent/questions.py +71 -0
  101. braid_coding_agent/render/__init__.py +56 -0
  102. braid_coding_agent/render/batch.py +66 -0
  103. braid_coding_agent/render/history.py +143 -0
  104. braid_coding_agent/render/stream.py +823 -0
  105. braid_coding_agent/render/theme.py +243 -0
  106. braid_coding_agent/sandbox/__init__.py +89 -0
  107. braid_coding_agent/sandbox/backend.py +184 -0
  108. braid_coding_agent/sandbox/bubblewrap.py +96 -0
  109. braid_coding_agent/sandbox/operations.py +301 -0
  110. braid_coding_agent/sandbox/policy.py +221 -0
  111. braid_coding_agent/sandbox/proxy.py +320 -0
  112. braid_coding_agent/sandbox/seatbelt.py +222 -0
  113. braid_coding_agent/sdk/__init__.py +31 -0
  114. braid_coding_agent/sdk/async_client.py +366 -0
  115. braid_coding_agent/sdk/client.py +386 -0
  116. braid_coding_agent/sdk/errors.py +52 -0
  117. braid_coding_agent/sdk/events.py +162 -0
  118. braid_coding_agent/sdk/types.py +63 -0
  119. braid_coding_agent/sdk/wire.py +59 -0
  120. braid_coding_agent/server/__init__.py +54 -0
  121. braid_coding_agent/server/errors.py +52 -0
  122. braid_coding_agent/server/http_server.py +419 -0
  123. braid_coding_agent/server/hub.py +530 -0
  124. braid_coding_agent/server/openapi.py +157 -0
  125. braid_coding_agent/server/registry.py +354 -0
  126. braid_coding_agent/server/router.py +275 -0
  127. braid_coding_agent/server/run.py +148 -0
  128. braid_coding_agent/server/schema.py +194 -0
  129. braid_coding_agent/server/service.py +975 -0
  130. braid_coding_agent/session/__init__.py +293 -0
  131. braid_coding_agent/session/agent_session.py +2706 -0
  132. braid_coding_agent/session/context_breakdown.py +302 -0
  133. braid_coding_agent/session/discovery.py +212 -0
  134. braid_coding_agent/session/entries.py +809 -0
  135. braid_coding_agent/session/evidence.py +295 -0
  136. braid_coding_agent/session/lock.py +176 -0
  137. braid_coding_agent/session/manager.py +1185 -0
  138. braid_coding_agent/session/plan.py +243 -0
  139. braid_coding_agent/session/plan_mode.py +423 -0
  140. braid_coding_agent/session/projection.py +262 -0
  141. braid_coding_agent/session/rewind.py +257 -0
  142. braid_coding_agent/session/status.py +240 -0
  143. braid_coding_agent/settings.py +94 -0
  144. braid_coding_agent/skills/__init__.py +70 -0
  145. braid_coding_agent/skills/loader.py +681 -0
  146. braid_coding_agent/startup/__init__.py +76 -0
  147. braid_coding_agent/startup/cache.py +72 -0
  148. braid_coding_agent/startup/diagnostics.py +37 -0
  149. braid_coding_agent/startup/monitor.py +245 -0
  150. braid_coding_agent/startup/phases.py +79 -0
  151. braid_coding_agent/startup/project.py +165 -0
  152. braid_coding_agent/startup/report.py +560 -0
  153. braid_coding_agent/startup/scheduler.py +347 -0
  154. braid_coding_agent/statusline.py +163 -0
  155. braid_coding_agent/subagents/__init__.py +22 -0
  156. braid_coding_agent/subagents/contract.py +75 -0
  157. braid_coding_agent/subagents/definitions.py +583 -0
  158. braid_coding_agent/subagents/registry.py +277 -0
  159. braid_coding_agent/subagents/runtime.py +610 -0
  160. braid_coding_agent/subagents/settings.py +156 -0
  161. braid_coding_agent/subagents/worktree.py +63 -0
  162. braid_coding_agent/tools/__init__.py +327 -0
  163. braid_coding_agent/tools/args.py +87 -0
  164. braid_coding_agent/tools/bash.py +359 -0
  165. braid_coding_agent/tools/edit.py +298 -0
  166. braid_coding_agent/tools/edit_diff.py +344 -0
  167. braid_coding_agent/tools/find.py +158 -0
  168. braid_coding_agent/tools/grep.py +305 -0
  169. braid_coding_agent/tools/ignore.py +198 -0
  170. braid_coding_agent/tools/ls.py +127 -0
  171. braid_coding_agent/tools/mutation_queue.py +90 -0
  172. braid_coding_agent/tools/operations.py +274 -0
  173. braid_coding_agent/tools/output_accumulator.py +282 -0
  174. braid_coding_agent/tools/output_store.py +244 -0
  175. braid_coding_agent/tools/path_utils.py +91 -0
  176. braid_coding_agent/tools/plan.py +141 -0
  177. braid_coding_agent/tools/prompt_notes.py +52 -0
  178. braid_coding_agent/tools/question.py +180 -0
  179. braid_coding_agent/tools/read.py +223 -0
  180. braid_coding_agent/tools/submit_plan.py +102 -0
  181. braid_coding_agent/tools/truncate.py +423 -0
  182. braid_coding_agent/tools/write.py +100 -0
  183. braid_coding_agent/untrusted.py +50 -0
  184. braid_coding_agent/verify/__init__.py +78 -0
  185. braid_coding_agent/verify/runner.py +260 -0
  186. braid_coding_agent/verify/settings.py +64 -0
  187. braid_coding_agent/verify/tool.py +143 -0
  188. braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
  189. braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
  190. braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
  191. braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
  192. braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,76 @@
1
+ """启动生命周期:阶段策略、检查点监控、后台调度与缓存。
2
+
3
+ 这一层只依赖标准库,导入它不应拉起模型、工具、终端渲染或网络客户端。CLI 在
4
+ 参数解析之后才导入真正的装配链路;启动监控与调度器必须先于装配可用,才能在
5
+ ``/monitor`` 里如实记录每一段耗时。
6
+
7
+ 导出名按需导入:``--version`` 与 ``--help`` 不需要调度器,聚合导入会把
8
+ ``asyncio`` 与缓存模块一起拉起来。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import importlib
14
+ from typing import TYPE_CHECKING
15
+
16
+ if TYPE_CHECKING:
17
+ from braid_coding_agent.startup.monitor import (
18
+ Checkpoint,
19
+ StartupMonitor,
20
+ StartupSnapshot,
21
+ default_monitor,
22
+ )
23
+ from braid_coding_agent.startup.phases import (
24
+ INIT_SPECS,
25
+ InitPolicy,
26
+ InitSpec,
27
+ StartupPhase,
28
+ )
29
+ from braid_coding_agent.startup.scheduler import (
30
+ BackgroundScheduler,
31
+ ScheduledTask,
32
+ SchedulerFullError,
33
+ TaskPriority,
34
+ )
35
+
36
+ _LAZY_EXPORTS: dict[str, str] = {
37
+ "Checkpoint": "braid_coding_agent.startup.monitor",
38
+ "StartupMonitor": "braid_coding_agent.startup.monitor",
39
+ "StartupSnapshot": "braid_coding_agent.startup.monitor",
40
+ "default_monitor": "braid_coding_agent.startup.monitor",
41
+ "INIT_SPECS": "braid_coding_agent.startup.phases",
42
+ "InitPolicy": "braid_coding_agent.startup.phases",
43
+ "InitSpec": "braid_coding_agent.startup.phases",
44
+ "StartupPhase": "braid_coding_agent.startup.phases",
45
+ "BackgroundScheduler": "braid_coding_agent.startup.scheduler",
46
+ "ScheduledTask": "braid_coding_agent.startup.scheduler",
47
+ "SchedulerFullError": "braid_coding_agent.startup.scheduler",
48
+ "TaskPriority": "braid_coding_agent.startup.scheduler",
49
+ }
50
+
51
+
52
+ def __getattr__(name: str) -> object:
53
+ """按需导入导出名。"""
54
+ module_name = _LAZY_EXPORTS.get(name)
55
+ if module_name is None:
56
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
57
+ module = importlib.import_module(module_name)
58
+ value = getattr(module, name)
59
+ globals()[name] = value
60
+ return value
61
+
62
+
63
+ __all__ = [
64
+ "INIT_SPECS",
65
+ "BackgroundScheduler",
66
+ "Checkpoint",
67
+ "InitPolicy",
68
+ "InitSpec",
69
+ "ScheduledTask",
70
+ "SchedulerFullError",
71
+ "StartupMonitor",
72
+ "StartupPhase",
73
+ "StartupSnapshot",
74
+ "TaskPriority",
75
+ "default_monitor",
76
+ ]
@@ -0,0 +1,72 @@
1
+ """JSON 文件缓存的公共读写。
2
+
3
+ 缓存文件带结构版本与逐条指纹。读取失败、版本不符或单条结构损坏时按空缓存处理;
4
+ 写不进去只记录警告,启动流程继续。缓存只影响速度,不能成为启动失败的新来源。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import logging
12
+ import os
13
+ from pathlib import Path
14
+
15
+ from braid_ai.types import JsonValue
16
+
17
+ __all__ = ["CACHE_VERSION", "JsonCacheFile", "file_fingerprint"]
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ #: 通用缓存结构版本。字段变化时提升它,旧文件自动失效。
22
+ CACHE_VERSION = 1
23
+
24
+
25
+ def file_fingerprint(path: Path, *, extra: str = "") -> str:
26
+ """文件内容变化的代理指纹:修改时间、大小与一段调用方上下文。
27
+
28
+ 不读文件正文。修改时间在同一纳秒内不变且大小恰好相同的改写不会被识别,
29
+ 这是为了避免每次启动都把全部文件读一遍而付出的已知代价。
30
+ """
31
+ stat = path.stat()
32
+ suffix = hashlib.sha256(extra.encode("utf-8")).hexdigest()[:12] if extra else ""
33
+ return f"{stat.st_mtime_ns}:{stat.st_size}:{suffix}"
34
+
35
+
36
+ class JsonCacheFile:
37
+ """一个带版本信封与字符串键的 JSON 缓存文件。"""
38
+
39
+ def __init__(self, path: Path) -> None:
40
+ self.path = path
41
+
42
+ def load(self) -> dict[str, dict[str, JsonValue]]:
43
+ if not self.path.is_file():
44
+ return {}
45
+ try:
46
+ payload: JsonValue = json.loads(self.path.read_text(encoding="utf-8-sig"))
47
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
48
+ logger.debug("忽略无法读取的缓存 %s:%s", self.path, exc)
49
+ return {}
50
+ if not isinstance(payload, dict) or payload.get("version") != CACHE_VERSION:
51
+ return {}
52
+ entries = payload.get("entries")
53
+ if not isinstance(entries, dict):
54
+ return {}
55
+ result: dict[str, dict[str, JsonValue]] = {}
56
+ for key, value in entries.items():
57
+ if isinstance(value, dict):
58
+ result[str(key)] = dict(value)
59
+ return result
60
+
61
+ def save(self, entries: dict[str, dict[str, JsonValue]]) -> None:
62
+ payload = {"version": CACHE_VERSION, "entries": entries}
63
+ temporary = self.path.with_name(self.path.name + ".tmp")
64
+ try:
65
+ self.path.parent.mkdir(parents=True, exist_ok=True)
66
+ temporary.write_text(
67
+ json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
68
+ )
69
+ os.replace(temporary, self.path)
70
+ except OSError as exc:
71
+ logger.debug("无法写入缓存 %s:%s", self.path, exc)
72
+ temporary.unlink(missing_ok=True)
@@ -0,0 +1,37 @@
1
+ """后台初始化的诊断出口。
2
+
3
+ 启动后台任务时,诊断默认写 stderr。全屏界面接管终端之后,任何直接写 stderr 的
4
+ 内容都会落在 TUI 画布上;界面绑定显示函数以后,诊断改走记录区,由界面统一重绘。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ from collections.abc import Callable
11
+ from typing import Literal, TextIO
12
+
13
+ __all__ = ["DiagnosticRole", "RuntimeDiagnostics"]
14
+
15
+ type DiagnosticRole = Literal["muted", "warn", "err"]
16
+
17
+
18
+ class RuntimeDiagnostics:
19
+ """后台任务的诊断出口。
20
+
21
+ :param stream: 未绑定界面时的输出流,默认 ``sys.stderr``。
22
+ """
23
+
24
+ def __init__(self, *, stream: TextIO | None = None) -> None:
25
+ self._stream = stream
26
+ self._display: Callable[[str, DiagnosticRole], None] | None = None
27
+
28
+ def bind(self, display: Callable[[str, DiagnosticRole], None]) -> None:
29
+ """绑定界面显示函数;之后诊断直接进入界面记录。"""
30
+ self._display = display
31
+
32
+ def emit(self, text: str, *, role: DiagnosticRole = "warn") -> None:
33
+ """写一条诊断。"""
34
+ if self._display is not None:
35
+ self._display(text, role)
36
+ return
37
+ print(text, file=self._stream if self._stream is not None else sys.stderr)
@@ -0,0 +1,245 @@
1
+ """启动检查点与性能指标。
2
+
3
+ 启动耗时靠猜没有意义。每个初始化节点在发生时写一条检查点,``/monitor`` 直接读
4
+ 这一份记录;派生指标(TTFP、TTFU、TTFM)只在快照生成时计算,避免各调用方用
5
+ 不同口径各算一遍。
6
+
7
+ 进程起点取本模块第一次导入的时刻。它比解释器真正的进程创建时刻晚几毫秒,换来
8
+ 的是不需要平台相关的 ``psutil``;测量口径在文档里写明。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import time
14
+ from collections.abc import Callable, Mapping
15
+ from dataclasses import dataclass
16
+ from typing import Final
17
+
18
+ from braid_ai.types import JsonValue
19
+
20
+ __all__ = [
21
+ "PROCESS_START",
22
+ "Checkpoint",
23
+ "StartupMonitor",
24
+ "StartupSnapshot",
25
+ "default_monitor",
26
+ ]
27
+
28
+
29
+ #: 进程内第一次导入本模块的时刻,作为全部检查点的基准。
30
+ PROCESS_START: Final[float] = time.perf_counter()
31
+
32
+ #: 首次可交互时间取这些检查点里最早出现的一个。
33
+ _FIRST_RENDER_NAMES: Final[tuple[str, ...]] = (
34
+ "tui_first_render",
35
+ "repl_ready",
36
+ "print_ready",
37
+ )
38
+
39
+
40
+ def resident_memory_mb() -> float:
41
+ """当前进程的峰值常驻内存。``ru_maxrss`` 在 macOS 上是字节,在 Linux 上是 KiB。"""
42
+ import resource
43
+ import sys
44
+
45
+ peak = float(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
46
+ return peak / (1024.0 * 1024.0) if sys.platform == "darwin" else peak / 1024.0
47
+
48
+
49
+ @dataclass(slots=True, frozen=True)
50
+ class Checkpoint:
51
+ """一个初始化节点:名字、相对进程起点的耗时与可选说明。"""
52
+
53
+ name: str
54
+ elapsed_ms: float
55
+ detail: str | None = None
56
+
57
+ def wire(self) -> dict[str, JsonValue]:
58
+ payload: dict[str, JsonValue] = {
59
+ "name": self.name,
60
+ "elapsed_ms": round(self.elapsed_ms, 3),
61
+ }
62
+ if self.detail is not None:
63
+ payload["detail"] = self.detail
64
+ return payload
65
+
66
+
67
+ @dataclass(slots=True, frozen=True)
68
+ class StartupSnapshot:
69
+ """一次读取的完整启动状态。不可变,交给界面或协议序列化。"""
70
+
71
+ checkpoints: tuple[Checkpoint, ...]
72
+ metrics: Mapping[str, float]
73
+ counters: Mapping[str, int]
74
+ phase: str
75
+
76
+ def elapsed_ms(self, name: str) -> float | None:
77
+ """按名字取一个检查点;没有记录时返回 ``None``。"""
78
+ for item in self.checkpoints:
79
+ if item.name == name:
80
+ return item.elapsed_ms
81
+ return None
82
+
83
+ def wire(self) -> dict[str, JsonValue]:
84
+ return {
85
+ "phase": self.phase,
86
+ "checkpoints": [item.wire() for item in self.checkpoints],
87
+ "metrics": {name: round(value, 3) for name, value in self.metrics.items()},
88
+ "counters": dict(self.counters),
89
+ }
90
+
91
+
92
+ class StartupMonitor:
93
+ """启动过程的唯一记录点。
94
+
95
+ :param clock: 单调时钟,测试可以注入假时钟。
96
+ :param process_start: 进程起点;缺省用本模块导入时刻。
97
+ """
98
+
99
+ def __init__(
100
+ self,
101
+ *,
102
+ clock: Callable[[], float] = time.perf_counter,
103
+ process_start: float | None = None,
104
+ ) -> None:
105
+ self._clock = clock
106
+ self._process_start = PROCESS_START if process_start is None else process_start
107
+ self._checkpoints: list[Checkpoint] = []
108
+ self._seen: set[str] = set()
109
+ self._metrics: dict[str, float] = {}
110
+ self._counters: dict[str, int] = {}
111
+ self._phase = "bootstrap"
112
+
113
+ def begin(self, *, phase: str = "bootstrap") -> None:
114
+ """开始一次新的启动记录。进程起点保持不变,测试可反复调用。"""
115
+ self._checkpoints = []
116
+ self._seen = set()
117
+ self._metrics = {}
118
+ self._counters = {}
119
+ self._phase = phase
120
+ self.mark("process_start")
121
+
122
+ def mark(self, name: str, *, detail: str | None = None) -> None:
123
+ """记录一个检查点。同名检查点保留第一次出现的耗时。"""
124
+ if name in self._seen:
125
+ return
126
+ self._seen.add(name)
127
+ elapsed = max((self._clock() - self._process_start) * 1000.0, 0.0)
128
+ self._checkpoints.append(Checkpoint(name=name, elapsed_ms=elapsed, detail=detail))
129
+ if name in _FIRST_RENDER_NAMES:
130
+ self._metrics.setdefault("first_render_memory_mb", resident_memory_mb())
131
+
132
+ def metric(self, name: str, value: float) -> None:
133
+ """覆盖写入一条数值指标。"""
134
+ self._metrics[name] = float(value)
135
+
136
+ def increment(self, name: str, amount: int = 1) -> None:
137
+ """累加一条计数指标。"""
138
+ self._counters[name] = self._counters.get(name, 0) + amount
139
+
140
+ def metric_value(self, name: str, default: float = 0.0) -> float:
141
+ """读取一条指标的当前值,没有记录时返回默认值。"""
142
+ return self._metrics.get(name, default)
143
+
144
+ def set_phase(self, phase: str) -> None:
145
+ """记录当前阶段名,``/monitor`` 用它说明启动走到了哪一步。"""
146
+ self._phase = phase
147
+
148
+ @property
149
+ def phase(self) -> str:
150
+ return self._phase
151
+
152
+ def snapshot(self) -> StartupSnapshot:
153
+ """生成不可变快照,并补齐可派生的指标。"""
154
+ metrics = dict(self._metrics)
155
+ first_render = self._first_checkpoint(_FIRST_RENDER_NAMES)
156
+ if first_render is not None:
157
+ metrics.setdefault("ttfp_ms", first_render.elapsed_ms)
158
+ first_turn = self._first_checkpoint(("first_turn_start",))
159
+ if first_turn is not None:
160
+ metrics.setdefault("ttfu_ms", first_turn.elapsed_ms)
161
+ background_ready = self._first_checkpoint(("background_ready",))
162
+ if background_ready is not None:
163
+ metrics.setdefault("ttfm_ms", background_ready.elapsed_ms)
164
+ background_started = self._first_checkpoint(("background_started",))
165
+ cpu_ms = metrics.get("background_cpu_ms")
166
+ if background_started is not None and cpu_ms is not None:
167
+ wall_ms = max(
168
+ (self._clock() - self._process_start) * 1000.0 - background_started.elapsed_ms,
169
+ 0.001,
170
+ )
171
+ metrics.setdefault("background_cpu_percent", cpu_ms / wall_ms * 100.0)
172
+ mcp_durations = [
173
+ value
174
+ for name, value in metrics.items()
175
+ if name.startswith("task.mcp.") and name.endswith(".duration_ms")
176
+ ]
177
+ if mcp_durations:
178
+ metrics.setdefault("mcp_startup_ms", max(mcp_durations))
179
+ cache_hits = self._counters.get("mcp_servers_cached", 0) + self._counters.get(
180
+ "skill_cache_hit", 0
181
+ )
182
+ cache_total = (
183
+ self._counters.get("mcp_servers_total", 0)
184
+ + self._counters.get("skill_cache_hit", 0)
185
+ + self._counters.get("skill_cache_miss", 0)
186
+ )
187
+ if cache_total:
188
+ metrics.setdefault("cache_hit_rate", cache_hits / cache_total)
189
+ return StartupSnapshot(
190
+ checkpoints=tuple(self._checkpoints),
191
+ metrics=metrics,
192
+ counters=dict(self._counters),
193
+ phase=self._phase,
194
+ )
195
+
196
+ def format_report(self) -> str:
197
+ """``/monitor`` 的文本形式。检查点与指标各一段,不混在一起。"""
198
+ snapshot = self.snapshot()
199
+ lines = [f"启动阶段:{snapshot.phase}", "", "检查点:"]
200
+ width = max((len(item.name) for item in snapshot.checkpoints), default=12)
201
+ for item in snapshot.checkpoints:
202
+ detail = f" {item.detail}" if item.detail else ""
203
+ lines.append(f" [BOOT] {item.name:<{width}} {item.elapsed_ms:8.1f} ms{detail}")
204
+ lines.extend(["", "指标:"])
205
+ labels = {
206
+ "ttfp_ms": "首次可交互",
207
+ "ttfu_ms": "首次可处理任务",
208
+ "ttfm_ms": "完整功能就绪",
209
+ "import_ms": "模块导入",
210
+ "config_load_ms": "配置读取",
211
+ "mcp_startup_ms": "最慢 MCP 服务器",
212
+ "mcp_cache_hit_rate": "MCP 目录缓存命中率",
213
+ "skill_cache_hit_rate": "技能元信息缓存命中率",
214
+ "cache_hit_rate": "缓存整体命中率",
215
+ "first_render_memory_mb": "首次渲染内存",
216
+ "background_cpu_ms": "后台 CPU 时间",
217
+ "background_cpu_percent": "后台 CPU 占用",
218
+ }
219
+ for name, value in snapshot.metrics.items():
220
+ label = labels.get(name)
221
+ text = f" {name:<24} {value:10.2f}"
222
+ if label is not None:
223
+ text += f" {label}"
224
+ lines.append(text)
225
+ if snapshot.counters:
226
+ lines.extend(["", "计数:"])
227
+ for name, value in sorted(snapshot.counters.items()):
228
+ lines.append(f" {name:<24} {value}")
229
+ return "\n".join(lines)
230
+
231
+ def _first_checkpoint(self, names: tuple[str, ...]) -> Checkpoint | None:
232
+ found = {item.name: item for item in self._checkpoints if item.name in names}
233
+ for name in names:
234
+ item = found.get(name)
235
+ if item is not None:
236
+ return item
237
+ return None
238
+
239
+
240
+ _DEFAULT_MONITOR = StartupMonitor()
241
+
242
+
243
+ def default_monitor() -> StartupMonitor:
244
+ """进程级监控器。CLI 每次运行会 ``begin``,测试可以直接造独立实例。"""
245
+ return _DEFAULT_MONITOR
@@ -0,0 +1,79 @@
1
+ """初始化任务分级:Required、Eager、Lazy、Manual。
2
+
3
+ 这张表是文档与 ``/monitor`` 共用的清单。当前版本没有实现的能力照样列出,
4
+ ``implemented`` 标成 ``False``;用户能看到某个能力属于哪一级、为何还没接上。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from typing import Literal
11
+
12
+ __all__ = ["INIT_SPECS", "InitPolicy", "InitSpec", "StartupPhase"]
13
+
14
+ type StartupPhase = Literal["bootstrap", "first_render", "background", "on_demand"]
15
+ type InitPolicy = Literal["required", "eager", "lazy", "manual"]
16
+
17
+
18
+ @dataclass(slots=True, frozen=True)
19
+ class InitSpec:
20
+ """一项启动能力:阶段、策略、说明与是否已经实现。"""
21
+
22
+ name: str
23
+ phase: StartupPhase
24
+ policy: InitPolicy
25
+ description: str
26
+ implemented: bool = True
27
+
28
+
29
+ INIT_SPECS: tuple[InitSpec, ...] = (
30
+ InitSpec("cli.args", "bootstrap", "required", "解析命令行参数并校验互斥组合"),
31
+ InitSpec("config", "bootstrap", "required", "读取全局、项目与显式配置文件"),
32
+ InitSpec("security", "bootstrap", "required", "权限引擎、沙箱与 MCP 信任检查先于外部操作"),
33
+ InitSpec("session", "first_render", "required", "建立会话、装配工具与首次渲染"),
34
+ InitSpec("mcp.catalog", "first_render", "required", "从缓存读取 MCP 工具目录并注册元信息"),
35
+ InitSpec(
36
+ "skills.metadata",
37
+ "first_render",
38
+ "required",
39
+ "技能元信息随会话装配扫描;缓存命中时只比对文件指纹,正文按需读取",
40
+ ),
41
+ InitSpec("model.metadata", "first_render", "required", "合并模型目录缓存,离线可用"),
42
+ InitSpec(
43
+ "config.cache",
44
+ "bootstrap",
45
+ "required",
46
+ "配置解析缓存尚未实现:当前每次启动直接读取并合并配置文件",
47
+ False,
48
+ ),
49
+ InitSpec("mcp.servers", "background", "eager", "后台连接 MCP 服务器并刷新工具目录"),
50
+ InitSpec(
51
+ "model.preflight",
52
+ "background",
53
+ "lazy",
54
+ "真实端点连通性预检尚未实现:当前只合并离线模型目录并解析凭证",
55
+ False,
56
+ ),
57
+ InitSpec("subagents.metadata", "background", "eager", "扫描子代理定义并写入元信息缓存"),
58
+ InitSpec(
59
+ "plugin.manifest_cache",
60
+ "background",
61
+ "eager",
62
+ "插件清单缓存尚未实现:当前扩展只有配置加载,没有插件清单与安装目录",
63
+ False,
64
+ ),
65
+ InitSpec(
66
+ "cli.runtime_cache",
67
+ "bootstrap",
68
+ "required",
69
+ "CLI 模块加载缓存尚未实现:当前依赖 Python 自身的字节码缓存",
70
+ False,
71
+ ),
72
+ InitSpec("project.info", "background", "eager", "读取项目根目录、Git 分支与提交"),
73
+ InitSpec("mcp.tools", "on_demand", "lazy", "调用 mcp_load_tool 时载入完整工具 Schema"),
74
+ InitSpec("project.git_diff", "on_demand", "lazy", "首次查看 diff 时计算工作树差异"),
75
+ InitSpec("code_index", "on_demand", "lazy", "代码索引与 RAG 检索尚未实现", False),
76
+ InitSpec("browser", "on_demand", "lazy", "浏览器工具尚未实现", False),
77
+ InitSpec("plugin.runtime", "on_demand", "lazy", "插件清单缓存与按需运行尚未实现", False),
78
+ InitSpec("debug.tools", "on_demand", "manual", "调试与诊断工具仅在显式命令下装载"),
79
+ )
@@ -0,0 +1,165 @@
1
+ """项目信息缓存:根目录、项目类型与 Git 分支/提交。
2
+
3
+ 启动时扫描项目目录只是为状态栏与后续命令准备事实,不参与安全判定。缓存按项目
4
+ 根目录的标记文件与 ``.git`` 状态失效;工作树内容变化不会触发重新扫描,分支切换
5
+ 与提交会改变 ``HEAD``/``index`` 的修改时间,因此能识别出来。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import shutil
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ from braid_ai.types import JsonValue
16
+ from braid_coding_agent.startup.cache import JsonCacheFile, file_fingerprint
17
+
18
+ __all__ = ["ProjectCache", "ProjectInfo", "project_fingerprint"]
19
+
20
+ #: 识别项目类型用的标记文件。顺序决定同一目录下多种标记同时存在时的首选类型。
21
+ _MARKERS: tuple[tuple[str, str], ...] = (
22
+ ("pyproject.toml", "python"),
23
+ ("Cargo.toml", "rust"),
24
+ ("go.mod", "go"),
25
+ ("package.json", "node"),
26
+ ("pom.xml", "java"),
27
+ ("build.gradle", "java"),
28
+ ("Gemfile", "ruby"),
29
+ )
30
+
31
+ _GIT_TIMEOUT_SECONDS = 5.0
32
+
33
+
34
+ @dataclass(slots=True, frozen=True)
35
+ class ProjectInfo:
36
+ """一次扫描得到的只读事实。"""
37
+
38
+ cwd: str
39
+ root: str
40
+ kind: str
41
+ git_branch: str | None = None
42
+ git_commit: str | None = None
43
+
44
+ def wire(self) -> dict[str, JsonValue]:
45
+ return {
46
+ "cwd": self.cwd,
47
+ "root": self.root,
48
+ "kind": self.kind,
49
+ "git_branch": self.git_branch,
50
+ "git_commit": self.git_commit,
51
+ }
52
+
53
+ @classmethod
54
+ def from_wire(cls, raw: JsonValue) -> ProjectInfo | None:
55
+ if not isinstance(raw, dict):
56
+ return None
57
+ values = [raw.get(key) for key in ("cwd", "root", "kind")]
58
+ if not all(isinstance(value, str) for value in values):
59
+ return None
60
+ branch = raw.get("git_branch")
61
+ commit = raw.get("git_commit")
62
+ if branch is not None and not isinstance(branch, str):
63
+ return None
64
+ if commit is not None and not isinstance(commit, str):
65
+ return None
66
+ return cls(
67
+ cwd=values[0], # type: ignore[arg-type]
68
+ root=values[1], # type: ignore[arg-type]
69
+ kind=values[2], # type: ignore[arg-type]
70
+ git_branch=branch,
71
+ git_commit=commit,
72
+ )
73
+
74
+
75
+ def project_fingerprint(cwd: str | Path) -> str:
76
+ """项目状态指纹:向上每一层的标记文件、``.git/HEAD`` 与 ``.git/index``。"""
77
+ current = Path(cwd).expanduser().resolve()
78
+ parts: list[str] = [str(current)]
79
+ for directory in (current, *current.parents):
80
+ for name, _ in _MARKERS:
81
+ path = directory / name
82
+ if path.is_file():
83
+ parts.append(f"{path}:{file_fingerprint(path)}")
84
+ for name in ("HEAD", "index"):
85
+ path = directory / ".git" / name
86
+ if path.is_file():
87
+ parts.append(f"{path}:{file_fingerprint(path)}")
88
+ return "\n".join(parts)
89
+
90
+
91
+ class ProjectCache:
92
+ """``<agent_dir>/project_cache.json`` 的读写与扫描入口。"""
93
+
94
+ def __init__(self, agent_dir: Path) -> None:
95
+ self._file = JsonCacheFile(Path(agent_dir) / "project_cache.json")
96
+
97
+ def load(self, cwd: str) -> ProjectInfo | None:
98
+ raw = self._file.load().get(cwd)
99
+ if raw is None or raw.get("fingerprint") != project_fingerprint(cwd):
100
+ return None
101
+ return ProjectInfo.from_wire(raw.get("info"))
102
+
103
+ async def scan(self, cwd: str) -> ProjectInfo:
104
+ """扫描项目信息并写入缓存。Git 命令有独立超时,超时即取消子进程。"""
105
+ cached = self.load(cwd)
106
+ if cached is not None:
107
+ return cached
108
+ info = _scan_sync(cwd)
109
+ if info.git_branch is None and shutil.which("git") is not None:
110
+ branch, commit = await _read_git(cwd)
111
+ info = ProjectInfo(
112
+ cwd=info.cwd,
113
+ root=info.root,
114
+ kind=info.kind,
115
+ git_branch=branch,
116
+ git_commit=commit,
117
+ )
118
+ entries = self._file.load()
119
+ entries[cwd] = {
120
+ "fingerprint": project_fingerprint(cwd),
121
+ "info": info.wire(),
122
+ }
123
+ self._file.save(entries)
124
+ return info
125
+
126
+
127
+ def _scan_sync(cwd: str) -> ProjectInfo:
128
+ root = Path(cwd).expanduser().resolve()
129
+ kind = "unknown"
130
+ for directory in (root, *root.parents):
131
+ matched = next(
132
+ ((name, kind_name) for name, kind_name in _MARKERS if (directory / name).is_file()),
133
+ None,
134
+ )
135
+ if (directory / ".git").exists() or matched is not None:
136
+ root = directory
137
+ if matched is not None:
138
+ kind = matched[1]
139
+ break
140
+ return ProjectInfo(cwd=str(Path(cwd).expanduser().resolve()), root=str(root), kind=kind)
141
+
142
+
143
+ async def _read_git(cwd: str) -> tuple[str | None, str | None]:
144
+ branch = await _git(cwd, "rev-parse", "--abbrev-ref", "HEAD")
145
+ commit = await _git(cwd, "rev-parse", "HEAD")
146
+ return branch, commit
147
+
148
+
149
+ async def _git(cwd: str, *args: str) -> str | None:
150
+ process = await asyncio.create_subprocess_exec(
151
+ "git",
152
+ *args,
153
+ cwd=cwd,
154
+ stdout=asyncio.subprocess.PIPE,
155
+ stderr=asyncio.subprocess.PIPE,
156
+ )
157
+ try:
158
+ stdout, _ = await asyncio.wait_for(process.communicate(), _GIT_TIMEOUT_SECONDS)
159
+ except TimeoutError as exc:
160
+ process.kill()
161
+ await process.wait()
162
+ raise RuntimeError(f"git {' '.join(args)} 超过 {_GIT_TIMEOUT_SECONDS:g} 秒未完成") from exc
163
+ if process.returncode != 0:
164
+ return None
165
+ return stdout.decode("utf-8", errors="replace").strip() or None