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,98 @@
1
+ """提示词组装:分节构建、上下文文件发现、分节差分。
2
+
3
+ 这一层只做**文本**:把工具、规则、项目说明拼成有条目的分节,并算出差量。
4
+ 它不碰转录、不碰请求参数——"把分节写进一条系统消息"是 Agent Loop 的事
5
+ (``braid_agent.loop.declare_tool_changes`` 管工具那一半,``PromptBuilder``
6
+ 管分节那一半)。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib
12
+ from typing import TYPE_CHECKING
13
+
14
+ if TYPE_CHECKING:
15
+ from braid_coding_agent.prompt.context_files import (
16
+ CONTEXT_FILE_CANDIDATES,
17
+ DEFAULT_MAX_TOTAL_CHARS,
18
+ ContextFile,
19
+ InstructionFileError,
20
+ apply_budget,
21
+ load_context_file_from_dir,
22
+ load_instruction_files,
23
+ load_project_context_files,
24
+ strip_bom,
25
+ )
26
+ from braid_coding_agent.prompt.project_context import (
27
+ ContextSnapshot,
28
+ ProjectContext,
29
+ )
30
+ from braid_coding_agent.prompt.system_prompt import (
31
+ DEFAULT_PREAMBLE,
32
+ DEFAULT_SELECTED_TOOLS,
33
+ PromptDocs,
34
+ Skill,
35
+ build_system_prompt,
36
+ build_system_prompt_sections,
37
+ diff_system_prompt_sections,
38
+ format_skills_for_prompt,
39
+ validate_section_names,
40
+ )
41
+
42
+ _LAZY_EXPORTS: dict[str, str] = {
43
+ "CONTEXT_FILE_CANDIDATES": "braid_coding_agent.prompt.context_files",
44
+ "DEFAULT_MAX_TOTAL_CHARS": "braid_coding_agent.prompt.context_files",
45
+ "ContextFile": "braid_coding_agent.prompt.context_files",
46
+ "InstructionFileError": "braid_coding_agent.prompt.context_files",
47
+ "apply_budget": "braid_coding_agent.prompt.context_files",
48
+ "load_context_file_from_dir": "braid_coding_agent.prompt.context_files",
49
+ "load_instruction_files": "braid_coding_agent.prompt.context_files",
50
+ "load_project_context_files": "braid_coding_agent.prompt.context_files",
51
+ "strip_bom": "braid_coding_agent.prompt.context_files",
52
+ "ContextSnapshot": "braid_coding_agent.prompt.project_context",
53
+ "ProjectContext": "braid_coding_agent.prompt.project_context",
54
+ "DEFAULT_PREAMBLE": "braid_coding_agent.prompt.system_prompt",
55
+ "DEFAULT_SELECTED_TOOLS": "braid_coding_agent.prompt.system_prompt",
56
+ "PromptDocs": "braid_coding_agent.prompt.system_prompt",
57
+ "Skill": "braid_coding_agent.prompt.system_prompt",
58
+ "build_system_prompt": "braid_coding_agent.prompt.system_prompt",
59
+ "build_system_prompt_sections": "braid_coding_agent.prompt.system_prompt",
60
+ "diff_system_prompt_sections": "braid_coding_agent.prompt.system_prompt",
61
+ "format_skills_for_prompt": "braid_coding_agent.prompt.system_prompt",
62
+ "validate_section_names": "braid_coding_agent.prompt.system_prompt",
63
+ }
64
+
65
+
66
+ def __getattr__(name: str) -> object:
67
+ """按需导入导出名。"""
68
+ module_name = _LAZY_EXPORTS.get(name)
69
+ if module_name is None:
70
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
71
+ module = importlib.import_module(module_name)
72
+ value = getattr(module, name)
73
+ globals()[name] = value
74
+ return value
75
+
76
+
77
+ __all__ = [
78
+ "CONTEXT_FILE_CANDIDATES",
79
+ "DEFAULT_MAX_TOTAL_CHARS",
80
+ "DEFAULT_PREAMBLE",
81
+ "DEFAULT_SELECTED_TOOLS",
82
+ "ContextFile",
83
+ "ContextSnapshot",
84
+ "InstructionFileError",
85
+ "ProjectContext",
86
+ "PromptDocs",
87
+ "Skill",
88
+ "apply_budget",
89
+ "build_system_prompt",
90
+ "build_system_prompt_sections",
91
+ "diff_system_prompt_sections",
92
+ "format_skills_for_prompt",
93
+ "load_context_file_from_dir",
94
+ "load_instruction_files",
95
+ "load_project_context_files",
96
+ "strip_bom",
97
+ "validate_section_names",
98
+ ]
@@ -0,0 +1,253 @@
1
+ """项目上下文文件:把仓库里的 ``AGENTS.md`` 与配置里的额外指令找出来。
2
+
3
+ ## 找哪几个名字,按什么顺序
4
+
5
+ 一个目录里只取**一个**文件,候选名单按优先级排:
6
+
7
+ ```text
8
+ AGENTS.override.md > AGENTS.md > AGENTS.MD > CLAUDE.md > CLAUDE.MD
9
+ ```
10
+
11
+ 大小写两套名字都要认,是因为 macOS 与 Linux 上同一份文件可能以不同大小写存在。
12
+
13
+ ## 从哪里往上找
14
+
15
+ ```text
16
+ ~/.braid/AGENTS.md ← 全局,最先渲染(用户级偏好)
17
+ /repo/AGENTS.md ← 仓库级
18
+ /repo/packages/app/AGENTS.md ← 包级
19
+ ```
20
+
21
+ 越靠近 ``cwd`` 的文件排在越后面。模型读提示词是顺序读的,后面出现的内容更容易
22
+ 覆盖前面的判断,所以最具体的规则放最后。
23
+
24
+ ## 额外指令
25
+
26
+ 配置里的 ``instructions`` 是显式清单:相对路径、绝对路径与 glob 都认,命中结果按
27
+ 路径排序并去重,排在自动发现的 ``AGENTS.md`` 之后。字面路径不存在、文件不是 UTF-8
28
+ 一律报错——自动发现的文件是可选输入,显式写下的清单不是。
29
+
30
+ ## 总长度上限
31
+
32
+ 自动发现的文件与额外指令共用 32k 字符预算,并在真正超限时**从优先级最低的一端**
33
+ 开始截断:离 ``cwd`` 最近的规则最不可替代,先牺牲的是全局与仓库根的那一份。截断处
34
+ 留下显式标记,模型与人都能看到"这里少了一段"。
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import glob
40
+ import os
41
+ from collections.abc import Sequence
42
+ from dataclasses import dataclass, replace
43
+ from pathlib import Path
44
+ from typing import Literal
45
+
46
+ #: 一个目录里按优先级排列的候选文件名。命中第一个就停。
47
+ CONTEXT_FILE_CANDIDATES: tuple[str, ...] = (
48
+ "AGENTS.override.md",
49
+ "AGENTS.md",
50
+ "AGENTS.MD",
51
+ "CLAUDE.md",
52
+ "CLAUDE.MD",
53
+ )
54
+
55
+ #: 全部上下文文件合计的字符上限。约等于 8k token,够放下多层 ``AGENTS.md``,
56
+ #: 又不至于把上下文窗口吃空。
57
+ DEFAULT_MAX_TOTAL_CHARS = 32_000
58
+
59
+ _BOM = "\ufeff"
60
+
61
+
62
+ class InstructionFileError(ValueError):
63
+ """配置里显式指定的额外指令文件不可用。装配阶段直接失败。"""
64
+
65
+
66
+ @dataclass(slots=True)
67
+ class ContextFile:
68
+ """一份项目说明文件:绝对路径 + 正文 + 呈现所需的统计信息。"""
69
+
70
+ path: str
71
+ content: str
72
+ #: 截断之前的原文字符数。``None`` 表示与 ``content`` 等长。
73
+ original_chars: int | None = None
74
+ truncated: bool = False
75
+ kind: Literal["global", "project", "instructions"] = "project"
76
+
77
+
78
+ def load_context_file_from_dir(directory: str | os.PathLike[str]) -> ContextFile | None:
79
+ """在**单个目录**里找一份上下文文件。找不到返回 ``None``。
80
+
81
+ 目录不存在、候选名是目录而非文件、读取失败,全部当作"这个目录没有"。
82
+ 上下文文件是可选输入,缺了它提示词照样能用,为它抛异常只会让 ``cwd`` 写错
83
+ 这种小问题变成整个进程起不来。
84
+ """
85
+ base = Path(directory)
86
+ for filename in CONTEXT_FILE_CANDIDATES:
87
+ candidate = base / filename
88
+ try:
89
+ if not candidate.is_file():
90
+ continue
91
+ return ContextFile(path=str(candidate), content=strip_bom(candidate.read_text("utf-8")))
92
+ except OSError:
93
+ continue
94
+ return None
95
+
96
+
97
+ def load_project_context_files(
98
+ cwd: str | os.PathLike[str],
99
+ *,
100
+ agent_dir: str | os.PathLike[str] | None = None,
101
+ max_total_chars: int = DEFAULT_MAX_TOTAL_CHARS,
102
+ ) -> list[ContextFile]:
103
+ """收集自动发现的项目说明文件。
104
+
105
+ :param cwd: 工作目录。从它开始沿父目录链一直找到文件系统根。
106
+ :param agent_dir: 全局配置目录(``~/.braid``)。全局 ``AGENTS.md`` 直接放在它下面
107
+ (``~/.braid/AGENTS.md``),与项目配置根 ``.braid`` 对称。为 ``None``
108
+ 表示不读全局文件。
109
+ :param max_total_chars: 合计字符上限;``0`` 表示不限制。
110
+ :return: 按渲染顺序排列:全局 → 最外层 → … → ``cwd``。
111
+
112
+ 去重只按**路径**。两条路径指向同一个文件(符号链接)会各自出现一次;这不影响
113
+ 正确性,只多花一点预算,而解析真实路径要处理 ``..``、大小写、网络盘,代价更高。
114
+ """
115
+ resolved_cwd = Path(cwd).expanduser().resolve()
116
+ files: list[ContextFile] = []
117
+ seen: set[str] = set()
118
+
119
+ if agent_dir is not None:
120
+ # 全局 AGENTS.md 就在配置根 ~/.braid 下,与项目级 <project>/.braid 对称。
121
+ global_file = load_context_file_from_dir(Path(agent_dir).expanduser().resolve())
122
+ if global_file is not None:
123
+ marked = replace(global_file, kind="global")
124
+ files.append(marked)
125
+ seen.add(marked.path)
126
+
127
+ ancestors: list[ContextFile] = []
128
+ current = resolved_cwd
129
+ while True:
130
+ found = load_context_file_from_dir(current)
131
+ if found is not None and found.path not in seen:
132
+ ancestors.insert(0, found) # 由内向外找,插到前面就变成由外向内
133
+ seen.add(found.path)
134
+ parent = current.parent
135
+ if parent == current:
136
+ break
137
+ current = parent
138
+
139
+ files.extend(ancestors)
140
+ return apply_budget(files, max_total_chars)
141
+
142
+
143
+ def load_instruction_files(
144
+ cwd: str | os.PathLike[str], patterns: Sequence[str]
145
+ ) -> list[ContextFile]:
146
+ """读取配置里显式写下的额外指令文件,按绝对路径排序去重。
147
+
148
+ :param cwd: 相对路径(含相对 glob)的解析基准。
149
+ :param patterns: ``instructions`` 数组。带 ``*?[`` 的按 glob 展开,没有命中属于
150
+ 正常情况;不带通配符的字面路径必须存在,否则抛出 :class:`InstructionFileError`。
151
+ :raises InstructionFileError: 字面路径不存在,或命中的文件读不出来。
152
+ """
153
+ base = Path(cwd).expanduser().resolve()
154
+ matches: set[str] = set()
155
+ for pattern in patterns:
156
+ expanded = os.path.expanduser(pattern)
157
+ absolute = os.path.isabs(expanded)
158
+ if _has_magic(expanded):
159
+ hits = (
160
+ glob.glob(expanded, recursive=True)
161
+ if absolute
162
+ else glob.glob(expanded, root_dir=str(base), recursive=True)
163
+ )
164
+ for hit in hits:
165
+ candidate = Path(hit) if absolute else base / hit
166
+ if candidate.is_file():
167
+ matches.add(str(candidate.resolve()))
168
+ continue
169
+ candidate = Path(expanded) if absolute else base / expanded
170
+ if not candidate.is_file():
171
+ raise InstructionFileError(f"额外指令文件不存在或不是文件:{pattern}")
172
+ matches.add(str(candidate.resolve()))
173
+
174
+ files: list[ContextFile] = []
175
+ for resolved in sorted(matches):
176
+ try:
177
+ text = Path(resolved).read_text(encoding="utf-8")
178
+ except (OSError, UnicodeDecodeError) as exc:
179
+ raise InstructionFileError(f"无法读取额外指令文件 {resolved}:{exc}") from exc
180
+ files.append(ContextFile(path=resolved, content=strip_bom(text), kind="instructions"))
181
+ return files
182
+
183
+
184
+ def _has_magic(pattern: str) -> bool:
185
+ return any(character in pattern for character in "*?[")
186
+
187
+
188
+ def strip_bom(text: str) -> str:
189
+ """去掉开头可能存在的 BOM。Windows 编辑器写入的 UTF-8 文件常带它。
190
+
191
+ 保留 BOM 会让提示词开头多一个不可见字符:模型偶尔会把它当成内容的一部分复述出来,
192
+ 而人看不出问题在哪。
193
+ """
194
+ return text[len(_BOM) :] if text.startswith(_BOM) else text
195
+
196
+
197
+ def apply_budget(files: list[ContextFile], max_total_chars: int) -> list[ContextFile]:
198
+ """按总字符上限裁剪,从**优先级最低**的一端开始。
199
+
200
+ 预算从"离 ``cwd`` 最近"的那份开始分配,剩余额度依次给更外层的文件。因此被截断的
201
+ 总是全局或仓库根的那份,而项目内最具体的规则保持完整。
202
+ """
203
+ if max_total_chars <= 0:
204
+ return files
205
+ total = sum(len(item.content) for item in files)
206
+ if total <= max_total_chars:
207
+ return files
208
+
209
+ allowances: dict[str, int] = {}
210
+ remaining = max_total_chars
211
+ for item in reversed(files):
212
+ allowances[item.path] = min(len(item.content), remaining)
213
+ remaining -= allowances[item.path]
214
+ if remaining <= 0:
215
+ break
216
+
217
+ trimmed: list[ContextFile] = []
218
+ for item in files:
219
+ if not item.content:
220
+ # 空文件不占预算,也没有可截断的内容;保留它,让提示词形状与磁盘一致。
221
+ trimmed.append(item)
222
+ continue
223
+ allowed = allowances.get(item.path, 0)
224
+ if allowed == 0:
225
+ continue
226
+ if allowed >= len(item.content):
227
+ trimmed.append(item)
228
+ continue
229
+ omitted = len(item.content) - allowed
230
+ original = item.original_chars if item.original_chars is not None else len(item.content)
231
+ trimmed.append(
232
+ ContextFile(
233
+ path=item.path,
234
+ content=f"{item.content[:allowed]}\n\n[... truncated {omitted} characters ...]",
235
+ original_chars=original,
236
+ truncated=True,
237
+ kind=item.kind,
238
+ )
239
+ )
240
+ return trimmed
241
+
242
+
243
+ __all__ = [
244
+ "CONTEXT_FILE_CANDIDATES",
245
+ "DEFAULT_MAX_TOTAL_CHARS",
246
+ "ContextFile",
247
+ "InstructionFileError",
248
+ "apply_budget",
249
+ "load_context_file_from_dir",
250
+ "load_instruction_files",
251
+ "load_project_context_files",
252
+ "strip_bom",
253
+ ]
@@ -0,0 +1,172 @@
1
+ """项目上下文快照:把两类规则合成一份可刷新的状态。
2
+
3
+ ``PromptBuilder.context_files`` 在装配期就固定了。Codex 与 Claude Code 也只在会话
4
+ 启动时读规则文件;S35 要的是"改完规则下一回合就生效",于是这里保存加载参数,让
5
+ ``AgentSession`` 在每次 ``prompt()`` 之前重读磁盘,按**原文内容哈希**判断有没有变化。
6
+
7
+ 哈希按截断前的原文与文件路径一起算:被 32k 预算裁掉的那半段发生变化,模型手上的
8
+ 文本没变,但磁盘规则确实变了,下一次刷新必须发现它。变化只更新 ``context_files``,
9
+ 系统消息的 ``project_context`` 补丁仍由既有的分节差分算出,协议形状不变。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import json
16
+ from collections.abc import Sequence
17
+ from dataclasses import dataclass, replace
18
+ from datetime import datetime
19
+ from pathlib import Path
20
+
21
+ from braid_ai.utils.clock import Clock, SystemClock
22
+ from braid_coding_agent.prompt.context_files import (
23
+ DEFAULT_MAX_TOTAL_CHARS,
24
+ ContextFile,
25
+ apply_budget,
26
+ load_instruction_files,
27
+ load_project_context_files,
28
+ )
29
+
30
+ _KIND_LABELS: dict[str, str] = {
31
+ "global": "全局",
32
+ "project": "项目",
33
+ "instructions": "指令",
34
+ }
35
+
36
+
37
+ @dataclass(slots=True, frozen=True)
38
+ class ContextSnapshot:
39
+ """一次加载的结果:生效的文件、内容指纹与呈现所需的数据。"""
40
+
41
+ files: tuple[ContextFile, ...]
42
+ digest: str
43
+ loaded_at_ms: int
44
+ changed_at_ms: int | None
45
+ max_total_chars: int
46
+ project_files_enabled: bool
47
+ instructions_enabled: bool
48
+ instructions: tuple[str, ...]
49
+ raw_chars: int
50
+
51
+ def status_lines(self) -> list[str]:
52
+ """``/context`` 的文本:来源开关、逐文件字符数、截断情况与变化时间。"""
53
+ used = sum(len(item.content) for item in self.files)
54
+ lines = [
55
+ "项目规则:"
56
+ f"{'开' if self.project_files_enabled else '关'} · 额外指令:"
57
+ f"{'开' if self.instructions_enabled else '关'} · 预算 {self.max_total_chars} 字符",
58
+ f"已加载 {len(self.files)} 个文件 · 合计 {used} 字符",
59
+ ]
60
+ for item in self.files:
61
+ suffix = f" · 已截断(原文 {item.original_chars} 字符)" if item.truncated else ""
62
+ label = _KIND_LABELS.get(item.kind, item.kind)
63
+ lines.append(f" [{label}] {item.path} · {len(item.content)} 字符{suffix}")
64
+ if self.changed_at_ms is None:
65
+ lines.append("最近变化:本次启动后未变化")
66
+ else:
67
+ lines.append(f"最近变化:{_format_ms(self.changed_at_ms)}")
68
+ return lines
69
+
70
+
71
+ class ProjectContext:
72
+ """持有加载参数,在两次提问之间重读规则文件。
73
+
74
+ 构造时读一次;:meth:`refresh` 返回 ``True`` 表示磁盘内容与上一份快照不同。禁用
75
+ 两类来源时完全不碰磁盘,便于 ``--no-project-context`` 与 ``--no-instructions``
76
+ 做隔离调试。
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ *,
82
+ cwd: str | Path,
83
+ agent_dir: str | Path | None = None,
84
+ instructions: Sequence[str] = (),
85
+ project_files: bool = True,
86
+ extra_instructions: bool = True,
87
+ max_total_chars: int = DEFAULT_MAX_TOTAL_CHARS,
88
+ clock: Clock | None = None,
89
+ ) -> None:
90
+ self._cwd = str(Path(cwd).expanduser().resolve())
91
+ self._agent_dir = (
92
+ str(Path(agent_dir).expanduser().resolve()) if agent_dir is not None else None
93
+ )
94
+ self._instructions = tuple(instructions)
95
+ self._project_files = project_files
96
+ self._extra_instructions = extra_instructions
97
+ self._max_total_chars = max_total_chars
98
+ self._clock: Clock = clock if clock is not None else SystemClock()
99
+ self._loaded_at_ms = self._clock.now_ms()
100
+ self._refresh_count = 0
101
+ self._snapshot = self._load(changed_at_ms=None)
102
+
103
+ @property
104
+ def snapshot(self) -> ContextSnapshot:
105
+ return self._snapshot
106
+
107
+ @property
108
+ def files(self) -> tuple[ContextFile, ...]:
109
+ """当前应当交给 ``PromptBuilder`` 的文件(已应用预算)。"""
110
+ return self._snapshot.files
111
+
112
+ @property
113
+ def instructions(self) -> tuple[str, ...]:
114
+ return self._instructions
115
+
116
+ @property
117
+ def refresh_count(self) -> int:
118
+ return self._refresh_count
119
+
120
+ def refresh(self) -> bool:
121
+ """重读磁盘;内容变化时更新快照并返回 ``True``。"""
122
+ candidate = self._load(changed_at_ms=self._snapshot.changed_at_ms)
123
+ self._refresh_count += 1
124
+ if candidate.digest == self._snapshot.digest:
125
+ return False
126
+ self._snapshot = replace(candidate, changed_at_ms=self._clock.now_ms())
127
+ return True
128
+
129
+ def status_lines(self) -> list[str]:
130
+ return self._snapshot.status_lines()
131
+
132
+ def _load(self, *, changed_at_ms: int | None) -> ContextSnapshot:
133
+ project = (
134
+ load_project_context_files(self._cwd, agent_dir=self._agent_dir, max_total_chars=0)
135
+ if self._project_files
136
+ else []
137
+ )
138
+ extra = (
139
+ load_instruction_files(self._cwd, self._instructions)
140
+ if self._extra_instructions
141
+ else []
142
+ )
143
+ seen = {item.path for item in project}
144
+ merged = [*project, *(item for item in extra if item.path not in seen)]
145
+ raw_chars = sum(len(item.content) for item in merged)
146
+ return ContextSnapshot(
147
+ files=tuple(apply_budget(merged, self._max_total_chars)),
148
+ digest=_digest(merged),
149
+ loaded_at_ms=self._loaded_at_ms,
150
+ changed_at_ms=changed_at_ms,
151
+ max_total_chars=self._max_total_chars,
152
+ project_files_enabled=self._project_files,
153
+ instructions_enabled=self._extra_instructions,
154
+ instructions=self._instructions,
155
+ raw_chars=raw_chars,
156
+ )
157
+
158
+
159
+ def _digest(files: Sequence[ContextFile]) -> str:
160
+ payload = json.dumps(
161
+ [[item.path, item.content] for item in files],
162
+ ensure_ascii=False,
163
+ separators=(",", ":"),
164
+ )
165
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
166
+
167
+
168
+ def _format_ms(timestamp_ms: int) -> str:
169
+ return datetime.fromtimestamp(timestamp_ms / 1000).strftime("%Y-%m-%d %H:%M:%S")
170
+
171
+
172
+ __all__ = ["ContextSnapshot", "ProjectContext"]