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,379 @@
|
|
|
1
|
+
"""运行时规则文件与项目信任记录。
|
|
2
|
+
|
|
3
|
+
``settings.json`` 由用户手工维护,字段顺序与内容都属于用户。运行时的
|
|
4
|
+
``/permission allow`` 不该改写它,因此另设两个文件:
|
|
5
|
+
|
|
6
|
+
- ``~/.braid/permissions.toml``:全局运行时规则;
|
|
7
|
+
- ``<cwd>/.braid/permissions.local.toml``:项目运行时规则。
|
|
8
|
+
|
|
9
|
+
文件用数组表保存规则,写入时整份重写。这两个文件由工具生成,不承诺保留注释;
|
|
10
|
+
用户手写的 ``settings.json`` 永远不被重写。
|
|
11
|
+
|
|
12
|
+
## 信任
|
|
13
|
+
|
|
14
|
+
``~/.braid/permission_trust.json`` 记录项目路径与 ``.braid/settings.json`` 的指纹。
|
|
15
|
+
未信任项目的 ``permissions.local.toml`` 只取 deny 规则;项目配置里的
|
|
16
|
+
``mode``、``default`` 与 allow / ask 规则都不生效。指纹只覆盖 ``settings.json``:
|
|
17
|
+
运行时写入 ``permissions.local.toml`` 是用户的显式动作,不该让项目立刻退回未信任。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import tomllib
|
|
26
|
+
from collections.abc import Mapping
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from datetime import UTC, datetime
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import cast
|
|
31
|
+
|
|
32
|
+
from braid_ai.types import JsonValue
|
|
33
|
+
from braid_coding_agent.config_files import CONFIG_FILE_NAME, PROJECT_CONFIG_DIR
|
|
34
|
+
from braid_coding_agent.permissions.model import (
|
|
35
|
+
PERMISSION_MODES,
|
|
36
|
+
PermissionAction,
|
|
37
|
+
PermissionMode,
|
|
38
|
+
RuleScope,
|
|
39
|
+
RuleTable,
|
|
40
|
+
ScopedRule,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
PERMISSIONS_FILE_NAME = "permissions.toml"
|
|
44
|
+
PROJECT_PERMISSIONS_FILE_NAME = "permissions.local.toml"
|
|
45
|
+
TRUST_FILE_NAME = "permission_trust.json"
|
|
46
|
+
PERMISSIONS_VERSION = 1
|
|
47
|
+
|
|
48
|
+
_RULE_KEYS = frozenset({"effect", "table", "pattern", "created_at"})
|
|
49
|
+
_FILE_KEYS = frozenset({"version", "mode", "rules"})
|
|
50
|
+
_TABLES: tuple[RuleTable, ...] = ("tools", "bash", "paths", "domains")
|
|
51
|
+
_ACTIONS: tuple[PermissionAction, ...] = ("allow", "ask", "deny")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class PermissionStoreError(ValueError):
|
|
55
|
+
"""规则文件不可读、结构不对或写入失败。消息带文件路径。"""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(slots=True, frozen=True)
|
|
59
|
+
class RuleFile:
|
|
60
|
+
"""一份运行时规则文件的内容。``mode`` 为空表示文件没有覆盖模式。"""
|
|
61
|
+
|
|
62
|
+
mode: PermissionMode | None
|
|
63
|
+
rules: tuple[ScopedRule, ...]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(slots=True, frozen=True)
|
|
67
|
+
class TrustRecord:
|
|
68
|
+
"""一个已信任项目的指纹与时间。时间只用于排查,不参与判定。"""
|
|
69
|
+
|
|
70
|
+
fingerprint: str
|
|
71
|
+
trusted_at: str
|
|
72
|
+
|
|
73
|
+
def to_json(self) -> dict[str, JsonValue]:
|
|
74
|
+
return {"fingerprint": self.fingerprint, "trusted_at": self.trusted_at}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class PermissionStore:
|
|
78
|
+
"""运行时规则文件与信任记录的读写入口。"""
|
|
79
|
+
|
|
80
|
+
def __init__(self, *, agent_dir: Path, cwd: str) -> None:
|
|
81
|
+
self.agent_dir = agent_dir
|
|
82
|
+
self.cwd = str(Path(cwd).resolve())
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def global_path(self) -> Path:
|
|
86
|
+
return self.agent_dir / PERMISSIONS_FILE_NAME
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def project_path(self) -> Path:
|
|
90
|
+
return Path(self.cwd) / PROJECT_CONFIG_DIR / PROJECT_PERMISSIONS_FILE_NAME
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def trust_path(self) -> Path:
|
|
94
|
+
return self.agent_dir / TRUST_FILE_NAME
|
|
95
|
+
|
|
96
|
+
def load_global(self) -> RuleFile:
|
|
97
|
+
return load_rule_file(self.global_path, scope="global", source=str(self.global_path))
|
|
98
|
+
|
|
99
|
+
def load_project(self, *, trusted: bool) -> RuleFile:
|
|
100
|
+
return load_rule_file(
|
|
101
|
+
self.project_path,
|
|
102
|
+
scope="project",
|
|
103
|
+
source=str(self.project_path),
|
|
104
|
+
trusted=trusted,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
def append_rule(self, rule: ScopedRule, *, replace: bool = False) -> RuleFile:
|
|
108
|
+
"""写入一条规则。同一文件里同表同模式的效果被替换。
|
|
109
|
+
|
|
110
|
+
``replace=False`` 时,若已有同模式但不同效果的规则,抛出
|
|
111
|
+
:class:`PermissionStoreError`。批准提示写入项目规则时走这条路:把已有的
|
|
112
|
+
deny 静默改成 allow 是放宽动作,必须由用户显式加 ``--force``。
|
|
113
|
+
"""
|
|
114
|
+
path = self._path_for(rule.scope)
|
|
115
|
+
current = load_rule_file(path, scope=rule.scope, source=str(path))
|
|
116
|
+
existing = next(
|
|
117
|
+
(
|
|
118
|
+
item
|
|
119
|
+
for item in current.rules
|
|
120
|
+
if (item.table, item.pattern) == (rule.table, rule.pattern)
|
|
121
|
+
),
|
|
122
|
+
None,
|
|
123
|
+
)
|
|
124
|
+
if existing is not None and existing.effect != rule.effect and not replace:
|
|
125
|
+
raise PermissionStoreError(
|
|
126
|
+
f'{path}: 已有 {rule.table} "{rule.pattern}" = {existing.effect};'
|
|
127
|
+
"要改成 allow 请加 --force"
|
|
128
|
+
)
|
|
129
|
+
merged = [
|
|
130
|
+
item
|
|
131
|
+
for item in current.rules
|
|
132
|
+
if (item.table, item.pattern) != (rule.table, rule.pattern)
|
|
133
|
+
]
|
|
134
|
+
merged.append(ScopedRule(rule.table, rule.pattern, rule.effect, rule.scope, str(path)))
|
|
135
|
+
write_rule_file(path, mode=current.mode, rules=tuple(merged))
|
|
136
|
+
return RuleFile(mode=current.mode, rules=tuple(merged))
|
|
137
|
+
|
|
138
|
+
def remove_rule(self, rule: ScopedRule) -> bool:
|
|
139
|
+
"""删除一条规则。规则不在该文件里时返回 ``False``。"""
|
|
140
|
+
path = self._path_for(rule.scope)
|
|
141
|
+
current = load_rule_file(path, scope=rule.scope, source=str(path))
|
|
142
|
+
kept = [
|
|
143
|
+
item
|
|
144
|
+
for item in current.rules
|
|
145
|
+
if (item.table, item.pattern) != (rule.table, rule.pattern)
|
|
146
|
+
]
|
|
147
|
+
if len(kept) == len(current.rules):
|
|
148
|
+
return False
|
|
149
|
+
write_rule_file(path, mode=current.mode, rules=tuple(kept))
|
|
150
|
+
return True
|
|
151
|
+
|
|
152
|
+
def write_mode(self, mode: PermissionMode, *, scope: RuleScope) -> None:
|
|
153
|
+
path = self._path_for(scope)
|
|
154
|
+
current = load_rule_file(path, scope=scope, source=str(path))
|
|
155
|
+
write_rule_file(path, mode=mode, rules=current.rules)
|
|
156
|
+
|
|
157
|
+
def reset(self, *, scope: RuleScope) -> int:
|
|
158
|
+
"""清空一份运行时规则文件,返回删除的规则数。"""
|
|
159
|
+
path = self._path_for(scope)
|
|
160
|
+
current = load_rule_file(path, scope=scope, source=str(path))
|
|
161
|
+
write_rule_file(path, mode=None, rules=())
|
|
162
|
+
return len(current.rules)
|
|
163
|
+
|
|
164
|
+
def is_project_trusted(self) -> bool:
|
|
165
|
+
records = load_trust(self.agent_dir)
|
|
166
|
+
record = records.get(self.cwd)
|
|
167
|
+
if record is None:
|
|
168
|
+
return False
|
|
169
|
+
try:
|
|
170
|
+
fingerprint = self.project_fingerprint()
|
|
171
|
+
except OSError:
|
|
172
|
+
return False
|
|
173
|
+
return record.fingerprint == fingerprint
|
|
174
|
+
|
|
175
|
+
def project_fingerprint(self) -> str:
|
|
176
|
+
config = Path(self.cwd) / PROJECT_CONFIG_DIR / CONFIG_FILE_NAME
|
|
177
|
+
payload = config.read_bytes() if config.is_file() else b""
|
|
178
|
+
return hashlib.sha256(payload).hexdigest()
|
|
179
|
+
|
|
180
|
+
def remember_project(self) -> TrustRecord:
|
|
181
|
+
records = load_trust(self.agent_dir)
|
|
182
|
+
record = TrustRecord(
|
|
183
|
+
fingerprint=self.project_fingerprint(),
|
|
184
|
+
trusted_at=datetime.now(UTC).isoformat(timespec="seconds"),
|
|
185
|
+
)
|
|
186
|
+
records[self.cwd] = record
|
|
187
|
+
save_trust(self.agent_dir, records)
|
|
188
|
+
return record
|
|
189
|
+
|
|
190
|
+
def revoke_project(self) -> bool:
|
|
191
|
+
records = load_trust(self.agent_dir)
|
|
192
|
+
if records.pop(self.cwd, None) is None:
|
|
193
|
+
return False
|
|
194
|
+
save_trust(self.agent_dir, records)
|
|
195
|
+
return True
|
|
196
|
+
|
|
197
|
+
def _path_for(self, scope: RuleScope) -> Path:
|
|
198
|
+
if scope == "global":
|
|
199
|
+
return self.global_path
|
|
200
|
+
if scope == "project":
|
|
201
|
+
return self.project_path
|
|
202
|
+
raise PermissionStoreError(f"{scope} 规则不能写入文件")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def load_rule_file(
|
|
206
|
+
path: Path,
|
|
207
|
+
*,
|
|
208
|
+
scope: RuleScope,
|
|
209
|
+
source: str,
|
|
210
|
+
trusted: bool = True,
|
|
211
|
+
) -> RuleFile:
|
|
212
|
+
"""读一份运行时规则文件。``trusted=False`` 时只保留 deny 规则与丢弃模式。"""
|
|
213
|
+
if not path.is_file():
|
|
214
|
+
return RuleFile(mode=None, rules=())
|
|
215
|
+
try:
|
|
216
|
+
text = path.read_text(encoding="utf-8-sig")
|
|
217
|
+
except OSError as exc:
|
|
218
|
+
raise PermissionStoreError(f"{path}: 无法读取权限规则文件:{exc}") from exc
|
|
219
|
+
except UnicodeDecodeError as exc:
|
|
220
|
+
raise PermissionStoreError(f"{path}: 权限规则文件不是 UTF-8:{exc}") from exc
|
|
221
|
+
try:
|
|
222
|
+
document = cast("Mapping[str, object]", tomllib.loads(text))
|
|
223
|
+
except tomllib.TOMLDecodeError as exc:
|
|
224
|
+
raise PermissionStoreError(f"{path}: 不是合法的 TOML:{exc}") from exc
|
|
225
|
+
|
|
226
|
+
unknown = sorted(set(document) - _FILE_KEYS)
|
|
227
|
+
if unknown:
|
|
228
|
+
raise PermissionStoreError(
|
|
229
|
+
f"{path}: 未知字段 {', '.join(unknown)}(可用: {', '.join(sorted(_FILE_KEYS))})"
|
|
230
|
+
)
|
|
231
|
+
version = document.get("version")
|
|
232
|
+
if version != PERMISSIONS_VERSION:
|
|
233
|
+
raise PermissionStoreError(
|
|
234
|
+
f"{path}: version 必须是 {PERMISSIONS_VERSION},收到 {version!r}"
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
mode: PermissionMode | None = None
|
|
238
|
+
raw_mode = document.get("mode")
|
|
239
|
+
if raw_mode is not None:
|
|
240
|
+
if not isinstance(raw_mode, str) or raw_mode not in PERMISSION_MODES:
|
|
241
|
+
raise PermissionStoreError(
|
|
242
|
+
f"{path}: mode 只支持 {', '.join(PERMISSION_MODES)},收到 {raw_mode!r}"
|
|
243
|
+
)
|
|
244
|
+
mode = raw_mode
|
|
245
|
+
|
|
246
|
+
raw_rules = document.get("rules", [])
|
|
247
|
+
if not isinstance(raw_rules, list):
|
|
248
|
+
raise PermissionStoreError(f"{path}: rules 必须是数组表")
|
|
249
|
+
rules: list[ScopedRule] = []
|
|
250
|
+
seen: set[tuple[str, str]] = set()
|
|
251
|
+
for index, raw in enumerate(cast("list[object]", raw_rules)):
|
|
252
|
+
spot = f"{path}: rules[{index}]"
|
|
253
|
+
if not isinstance(raw, dict):
|
|
254
|
+
raise PermissionStoreError(f"{spot} 必须是一个表")
|
|
255
|
+
entry = cast("Mapping[str, object]", raw)
|
|
256
|
+
unknown = sorted(set(entry) - _RULE_KEYS)
|
|
257
|
+
if unknown:
|
|
258
|
+
raise PermissionStoreError(
|
|
259
|
+
f"{spot}: 未知字段 {', '.join(unknown)}(可用: {', '.join(sorted(_RULE_KEYS))})"
|
|
260
|
+
)
|
|
261
|
+
effect = _as_action(entry.get("effect"), where=f"{spot}.effect")
|
|
262
|
+
table = _as_table(entry.get("table"), where=f"{spot}.table")
|
|
263
|
+
pattern = entry.get("pattern")
|
|
264
|
+
if not isinstance(pattern, str) or not pattern.strip():
|
|
265
|
+
raise PermissionStoreError(f"{spot}.pattern 必须是非空字符串")
|
|
266
|
+
if (table, pattern) in seen:
|
|
267
|
+
raise PermissionStoreError(f'{spot}: 同一文件里重复的规则 {table} "{pattern}"')
|
|
268
|
+
seen.add((table, pattern))
|
|
269
|
+
if not trusted and effect != "deny":
|
|
270
|
+
continue
|
|
271
|
+
rules.append(ScopedRule(table, pattern, effect, scope, source))
|
|
272
|
+
|
|
273
|
+
if not trusted:
|
|
274
|
+
mode = None
|
|
275
|
+
return RuleFile(mode=mode, rules=tuple(rules))
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def write_rule_file(
|
|
279
|
+
path: Path,
|
|
280
|
+
*,
|
|
281
|
+
mode: PermissionMode | None,
|
|
282
|
+
rules: tuple[ScopedRule, ...],
|
|
283
|
+
) -> None:
|
|
284
|
+
"""整份重写运行时规则文件。先写临时文件再替换,失败时旧文件不变。"""
|
|
285
|
+
lines = [f"version = {PERMISSIONS_VERSION}", ""]
|
|
286
|
+
if mode is not None:
|
|
287
|
+
lines.insert(1, f"mode = {_quote(mode)}")
|
|
288
|
+
for rule in rules:
|
|
289
|
+
lines.extend(
|
|
290
|
+
(
|
|
291
|
+
"[[rules]]",
|
|
292
|
+
f"effect = {_quote(rule.effect)}",
|
|
293
|
+
f"table = {_quote(rule.table)}",
|
|
294
|
+
f"pattern = {_quote(rule.pattern)}",
|
|
295
|
+
"",
|
|
296
|
+
)
|
|
297
|
+
)
|
|
298
|
+
text = "\n".join(lines).rstrip() + "\n"
|
|
299
|
+
temporary = path.with_suffix(path.suffix + ".tmp")
|
|
300
|
+
try:
|
|
301
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
302
|
+
temporary.write_text(text, encoding="utf-8")
|
|
303
|
+
os.replace(temporary, path)
|
|
304
|
+
except OSError as exc:
|
|
305
|
+
raise PermissionStoreError(f"{path}: 无法写入权限规则文件:{exc}") from exc
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def load_trust(agent_dir: Path) -> dict[str, TrustRecord]:
|
|
309
|
+
"""读信任表。文件不存在、读坏或结构不对都返回空表:宁可多问一次。"""
|
|
310
|
+
path = agent_dir / TRUST_FILE_NAME
|
|
311
|
+
if not path.is_file():
|
|
312
|
+
return {}
|
|
313
|
+
try:
|
|
314
|
+
payload: JsonValue = json.loads(path.read_text(encoding="utf-8-sig"))
|
|
315
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
316
|
+
return {}
|
|
317
|
+
if not isinstance(payload, dict):
|
|
318
|
+
return {}
|
|
319
|
+
raw_projects = payload.get("projects")
|
|
320
|
+
if not isinstance(raw_projects, dict):
|
|
321
|
+
return {}
|
|
322
|
+
records: dict[str, TrustRecord] = {}
|
|
323
|
+
for name, entry in raw_projects.items():
|
|
324
|
+
if not isinstance(entry, dict):
|
|
325
|
+
continue
|
|
326
|
+
fingerprint = entry.get("fingerprint")
|
|
327
|
+
trusted_at = entry.get("trusted_at")
|
|
328
|
+
if isinstance(fingerprint, str) and fingerprint:
|
|
329
|
+
records[str(name)] = TrustRecord(
|
|
330
|
+
fingerprint=fingerprint,
|
|
331
|
+
trusted_at=trusted_at if isinstance(trusted_at, str) else "",
|
|
332
|
+
)
|
|
333
|
+
return records
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def save_trust(agent_dir: Path, records: dict[str, TrustRecord]) -> None:
|
|
337
|
+
path = agent_dir / TRUST_FILE_NAME
|
|
338
|
+
payload = {"projects": {name: record.to_json() for name, record in records.items()}}
|
|
339
|
+
try:
|
|
340
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
341
|
+
path.write_text(
|
|
342
|
+
json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
|
|
343
|
+
encoding="utf-8",
|
|
344
|
+
)
|
|
345
|
+
except OSError as exc:
|
|
346
|
+
raise PermissionStoreError(f"{path}: 无法写入项目信任记录:{exc}") from exc
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _as_action(value: object, *, where: str) -> PermissionAction:
|
|
350
|
+
if not isinstance(value, str) or value not in _ACTIONS:
|
|
351
|
+
raise PermissionStoreError(f"{where} 只支持 {', '.join(_ACTIONS)},收到 {value!r}")
|
|
352
|
+
return value
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _as_table(value: object, *, where: str) -> RuleTable:
|
|
356
|
+
if not isinstance(value, str) or value not in _TABLES:
|
|
357
|
+
raise PermissionStoreError(f"{where} 只支持 {', '.join(_TABLES)},收到 {value!r}")
|
|
358
|
+
return value
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _quote(value: str) -> str:
|
|
362
|
+
"""TOML 基本字符串。JSON 的转义规则在这里与 TOML 兼容。"""
|
|
363
|
+
return json.dumps(value, ensure_ascii=False)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
__all__ = [
|
|
367
|
+
"PERMISSIONS_FILE_NAME",
|
|
368
|
+
"PERMISSIONS_VERSION",
|
|
369
|
+
"PROJECT_PERMISSIONS_FILE_NAME",
|
|
370
|
+
"TRUST_FILE_NAME",
|
|
371
|
+
"PermissionStore",
|
|
372
|
+
"PermissionStoreError",
|
|
373
|
+
"RuleFile",
|
|
374
|
+
"TrustRecord",
|
|
375
|
+
"load_rule_file",
|
|
376
|
+
"load_trust",
|
|
377
|
+
"save_trust",
|
|
378
|
+
"write_rule_file",
|
|
379
|
+
]
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""``/init``:扫描仓库、发一次独立模型请求、生成可审阅的 ``AGENTS.md`` 草稿。
|
|
2
|
+
|
|
3
|
+
扫描得到的**事实**(构建文件、验证命令、已有规则)由代码读出来;模型只负责把它们
|
|
4
|
+
写成 readable 的项目约定。验证命令章节由代码生成,模型写错一个字母也不会让草稿
|
|
5
|
+
带上一条仓库里跑不通的命令。
|
|
6
|
+
|
|
7
|
+
已有 ``AGENTS.md`` 时只把新章节追加到原文之后,返回的字符串严格以原文开头:
|
|
8
|
+
整篇重写会让团队手写的内容在一次 ``/init`` 里消失。生成过程走
|
|
9
|
+
:class:`~braid_ai.types.TranscriptContext` 里的一条独立对话,主会话转录里没有任何
|
|
10
|
+
提示词或草稿;结果以 ``custom`` 条目落盘,恢复会话时仍能查到这次生成。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import difflib
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import tomllib
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import cast
|
|
22
|
+
|
|
23
|
+
from braid_agent.types import StreamFn
|
|
24
|
+
from braid_ai.cancel import CancelToken
|
|
25
|
+
from braid_ai.types import (
|
|
26
|
+
AssistantMessage,
|
|
27
|
+
Model,
|
|
28
|
+
SimpleStreamOptions,
|
|
29
|
+
SystemMessage,
|
|
30
|
+
TextContent,
|
|
31
|
+
TranscriptContext,
|
|
32
|
+
Usage,
|
|
33
|
+
UserMessage,
|
|
34
|
+
)
|
|
35
|
+
from braid_ai.utils.clock import Clock, SystemClock
|
|
36
|
+
from braid_ai.wire import content_text
|
|
37
|
+
|
|
38
|
+
#: 独立请求的硬性超时。/init 不是主循环,卡住时不能让整个 REPL 等下去。
|
|
39
|
+
INIT_TIMEOUT_SECONDS = 120.0
|
|
40
|
+
#: 草稿的输出上限。一份 AGENTS.md 通常几十行,给太多只是多花钱。
|
|
41
|
+
INIT_MAX_TOKENS = 1200
|
|
42
|
+
|
|
43
|
+
INIT_SYSTEM_PROMPT = (
|
|
44
|
+
"You write concise AGENTS.md instructions for a coding agent. "
|
|
45
|
+
"Use only the material supplied by the user. Never invent commands, files, or tools. "
|
|
46
|
+
"Prefer short bullet points over prose. Do not wrap the answer in a code fence. "
|
|
47
|
+
"The agent will run the verification commands listed in the material; include them verbatim."
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
_TARGET_PATTERN = re.compile(r"^([A-Za-z0-9_.-]+):")
|
|
51
|
+
_VERIFICATION_KEYWORDS = ("pytest", "ruff", "pyright", "mypy", "black", "test", "lint", "check")
|
|
52
|
+
_TARGET_KEYWORDS = ("verify", "test", "lint", "check")
|
|
53
|
+
_TOOL_COMMANDS = {
|
|
54
|
+
"pytest": "uv run pytest -q",
|
|
55
|
+
"ruff": "uv run ruff check .",
|
|
56
|
+
"pyright": "uv run pyright",
|
|
57
|
+
"mypy": "uv run mypy .",
|
|
58
|
+
"black": "uv run black --check .",
|
|
59
|
+
}
|
|
60
|
+
_SKIP_NAMES = frozenset(
|
|
61
|
+
{
|
|
62
|
+
".git",
|
|
63
|
+
".venv",
|
|
64
|
+
"node_modules",
|
|
65
|
+
"__pycache__",
|
|
66
|
+
".pytest_cache",
|
|
67
|
+
".ruff_cache",
|
|
68
|
+
".scratch",
|
|
69
|
+
".workbuddy",
|
|
70
|
+
"dist",
|
|
71
|
+
"build",
|
|
72
|
+
"site-packages",
|
|
73
|
+
}
|
|
74
|
+
)
|
|
75
|
+
_CONFIG_NAMES: tuple[str, ...] = (
|
|
76
|
+
"Makefile",
|
|
77
|
+
"makefile",
|
|
78
|
+
"pyproject.toml",
|
|
79
|
+
"setup.cfg",
|
|
80
|
+
"tox.ini",
|
|
81
|
+
"pytest.ini",
|
|
82
|
+
"package.json",
|
|
83
|
+
"Cargo.toml",
|
|
84
|
+
"go.mod",
|
|
85
|
+
"requirements.txt",
|
|
86
|
+
"uv.lock",
|
|
87
|
+
".pre-commit-config.yaml",
|
|
88
|
+
"tsconfig.json",
|
|
89
|
+
)
|
|
90
|
+
_RULE_NAMES: tuple[str, ...] = ("AGENTS.md", "CLAUDE.md", "CONTRIBUTING.md", "README.md")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class InitError(RuntimeError):
|
|
94
|
+
"""/init 的材料或模型响应不可用。REPL 把它显示成一行错误,不写盘。"""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(slots=True, frozen=True)
|
|
98
|
+
class RepoFacts:
|
|
99
|
+
"""扫描结果:目录形状、构建文件、已识别命令与已有规则原文。"""
|
|
100
|
+
|
|
101
|
+
cwd: str
|
|
102
|
+
top_level: tuple[str, ...]
|
|
103
|
+
config_files: tuple[str, ...]
|
|
104
|
+
verification_commands: tuple[str, ...]
|
|
105
|
+
config_excerpts: tuple[tuple[str, str], ...]
|
|
106
|
+
existing_rules: tuple[tuple[str, str], ...]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(slots=True, frozen=True)
|
|
110
|
+
class InitDraft:
|
|
111
|
+
"""一次独立模型请求的文本与用量。用量给用户看,避免"悄悄花了一次钱"。"""
|
|
112
|
+
|
|
113
|
+
text: str
|
|
114
|
+
usage: Usage
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def scan_repository(cwd: str | Path) -> RepoFacts:
|
|
118
|
+
"""只读扫描仓库根目录,收集 ``/init`` 需要的材料。"""
|
|
119
|
+
root = Path(cwd).expanduser().resolve()
|
|
120
|
+
entries = sorted(root.iterdir(), key=lambda item: item.name) if root.is_dir() else ()
|
|
121
|
+
top_level = tuple(
|
|
122
|
+
f"{item.name}/" if item.is_dir() else item.name
|
|
123
|
+
for item in entries
|
|
124
|
+
if item.name not in _SKIP_NAMES
|
|
125
|
+
)[:60]
|
|
126
|
+
present = tuple(name for name in _CONFIG_NAMES if (root / name).is_file())
|
|
127
|
+
|
|
128
|
+
excerpts: list[tuple[str, str]] = []
|
|
129
|
+
commands: list[str] = []
|
|
130
|
+
|
|
131
|
+
def add(command: str) -> None:
|
|
132
|
+
if command and command not in commands:
|
|
133
|
+
commands.append(command)
|
|
134
|
+
|
|
135
|
+
for name in present:
|
|
136
|
+
text = _read_text(root / name)
|
|
137
|
+
if name in ("Makefile", "makefile"):
|
|
138
|
+
excerpts.append((name, "\n".join(text.splitlines()[:80])))
|
|
139
|
+
for line in text.splitlines():
|
|
140
|
+
if line.startswith("\t"):
|
|
141
|
+
command = line.strip()
|
|
142
|
+
if any(word in command for word in _VERIFICATION_KEYWORDS):
|
|
143
|
+
add(command)
|
|
144
|
+
continue
|
|
145
|
+
target = _TARGET_PATTERN.match(line)
|
|
146
|
+
if target and any(word in target.group(1) for word in _TARGET_KEYWORDS):
|
|
147
|
+
add(f"make {target.group(1)}")
|
|
148
|
+
elif name == "pyproject.toml":
|
|
149
|
+
parsed = tomllib.loads(text)
|
|
150
|
+
tool = _object_mapping(parsed.get("tool"))
|
|
151
|
+
keys = sorted(tool) if tool is not None else []
|
|
152
|
+
excerpts.append((name, "tool tables: " + ", ".join(keys)))
|
|
153
|
+
for key in keys:
|
|
154
|
+
command = _TOOL_COMMANDS.get(key)
|
|
155
|
+
if command is not None:
|
|
156
|
+
add(command)
|
|
157
|
+
elif name == "package.json":
|
|
158
|
+
parsed = _object_mapping(json.loads(text))
|
|
159
|
+
if parsed is None:
|
|
160
|
+
raise InitError(f"{name} 顶层必须是对象")
|
|
161
|
+
names = sorted(_object_mapping(parsed.get("scripts")) or {})
|
|
162
|
+
excerpts.append((name, "scripts: " + ", ".join(names)))
|
|
163
|
+
for script in names:
|
|
164
|
+
if any(word in script for word in _VERIFICATION_KEYWORDS):
|
|
165
|
+
add(f"npm run {script}")
|
|
166
|
+
else:
|
|
167
|
+
excerpts.append((name, "\n".join(text.splitlines()[:40])))
|
|
168
|
+
|
|
169
|
+
rules = tuple(
|
|
170
|
+
(name, _read_text(root / name, max_lines=80 if name == "README.md" else 200))
|
|
171
|
+
for name in _RULE_NAMES
|
|
172
|
+
if (root / name).is_file()
|
|
173
|
+
)
|
|
174
|
+
return RepoFacts(
|
|
175
|
+
cwd=str(root),
|
|
176
|
+
top_level=top_level,
|
|
177
|
+
config_files=present,
|
|
178
|
+
verification_commands=tuple(commands),
|
|
179
|
+
config_excerpts=tuple(excerpts),
|
|
180
|
+
existing_rules=rules,
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def build_init_instruction(facts: RepoFacts, existing: str) -> str:
|
|
185
|
+
"""把扫描事实与已有规则拼成独立请求的用户消息。"""
|
|
186
|
+
lines = [
|
|
187
|
+
"You are writing project instructions for a coding agent in this repository.",
|
|
188
|
+
"Use only facts present below. Never invent commands, paths, or tooling.",
|
|
189
|
+
"",
|
|
190
|
+
f"Working directory: {facts.cwd}",
|
|
191
|
+
"Top-level entries: " + (", ".join(facts.top_level) or "(empty)"),
|
|
192
|
+
"Build and config files: " + (", ".join(facts.config_files) or "(none)"),
|
|
193
|
+
"Recognized verification commands:",
|
|
194
|
+
*(f"- {command}" for command in facts.verification_commands),
|
|
195
|
+
"",
|
|
196
|
+
"=== build file excerpts ===",
|
|
197
|
+
]
|
|
198
|
+
for name, excerpt in facts.config_excerpts:
|
|
199
|
+
lines.extend([f"--- {name} ---", excerpt, ""])
|
|
200
|
+
lines.append("=== existing rule files ===")
|
|
201
|
+
for name, excerpt in facts.existing_rules:
|
|
202
|
+
lines.extend([f"--- {name} ---", excerpt, ""])
|
|
203
|
+
lines.extend(["=== current AGENTS.md ===", existing or "(no AGENTS.md yet)", "", "Task:"])
|
|
204
|
+
if existing:
|
|
205
|
+
lines.append(
|
|
206
|
+
"Output only the NEW bullet points or short sections to append to the existing "
|
|
207
|
+
"AGENTS.md. Do not repeat existing content, do not rewrite the file, and do not "
|
|
208
|
+
"include a top-level title. Plain Markdown only."
|
|
209
|
+
)
|
|
210
|
+
else:
|
|
211
|
+
lines.append(
|
|
212
|
+
"Output a complete, concise AGENTS.md draft in Markdown: a title, repository "
|
|
213
|
+
"layout, coding conventions, and a verification section with the commands above "
|
|
214
|
+
"written verbatim. Keep it under 80 lines. Plain Markdown only."
|
|
215
|
+
)
|
|
216
|
+
return "\n".join(lines)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def compose_draft(facts: RepoFacts, model_text: str, existing: str) -> str:
|
|
220
|
+
"""合成待写入的全文。已有规则时原文逐字保留,只追加新章节。"""
|
|
221
|
+
body = model_text.strip()
|
|
222
|
+
commands = _commands_section(facts, existing)
|
|
223
|
+
if not existing:
|
|
224
|
+
parts = [part for part in (body, commands) if part]
|
|
225
|
+
return "\n\n".join(parts).rstrip() + "\n" if parts else ""
|
|
226
|
+
if not body and not commands:
|
|
227
|
+
return existing
|
|
228
|
+
additions = "\n\n".join(part for part in (body, commands) if part)
|
|
229
|
+
separator = "" if existing.endswith("\n") else "\n"
|
|
230
|
+
return existing + separator + "\n## /init 补充\n\n" + additions.rstrip() + "\n"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _commands_section(facts: RepoFacts, existing: str) -> str:
|
|
234
|
+
missing = [command for command in facts.verification_commands if command not in existing]
|
|
235
|
+
if not missing:
|
|
236
|
+
return ""
|
|
237
|
+
lines = ["## 验证命令", "", "以下命令来自仓库里的构建文件:"]
|
|
238
|
+
lines.extend(f"- `{command}`" for command in missing)
|
|
239
|
+
return "\n".join(lines)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def diff_lines(path: str | Path, before: str, after: str) -> list[str]:
|
|
243
|
+
"""待写入内容的 unified diff,一行一条,供 REPL 逐行渲染。"""
|
|
244
|
+
name = Path(path).name
|
|
245
|
+
return list(
|
|
246
|
+
difflib.unified_diff(
|
|
247
|
+
before.splitlines(),
|
|
248
|
+
after.splitlines(),
|
|
249
|
+
fromfile=f"a/{name}",
|
|
250
|
+
tofile=f"b/{name}",
|
|
251
|
+
lineterm="",
|
|
252
|
+
)
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
async def request_rules_draft(
|
|
257
|
+
*,
|
|
258
|
+
model: Model,
|
|
259
|
+
stream_fn: StreamFn,
|
|
260
|
+
instruction: str,
|
|
261
|
+
signal: CancelToken | None = None,
|
|
262
|
+
clock: Clock | None = None,
|
|
263
|
+
) -> InitDraft:
|
|
264
|
+
"""发一次与主会话转录无关的模型请求,返回草稿文本与用量。"""
|
|
265
|
+
resolved_clock: Clock = clock if clock is not None else SystemClock()
|
|
266
|
+
now = resolved_clock.now_ms()
|
|
267
|
+
context = TranscriptContext(
|
|
268
|
+
messages=[
|
|
269
|
+
SystemMessage(timestamp=now, content=INIT_SYSTEM_PROMPT),
|
|
270
|
+
UserMessage(timestamp=now, content=[TextContent(text=instruction)]),
|
|
271
|
+
]
|
|
272
|
+
)
|
|
273
|
+
# 一次性请求:不留下缓存断点,否则要按缓存写的价格多付一次。
|
|
274
|
+
options = SimpleStreamOptions(signal=signal, max_tokens=INIT_MAX_TOKENS, cache_breakpoints=())
|
|
275
|
+
response: AssistantMessage = await stream_fn(model, context, options).result()
|
|
276
|
+
if response.stop_reason == "error":
|
|
277
|
+
raise InitError(f"规则草稿请求失败:{response.error_message or '未知错误'}")
|
|
278
|
+
if response.stop_reason in ("length", "aborted"):
|
|
279
|
+
raise InitError(f"规则草稿不完整(stop_reason={response.stop_reason}),已放弃写入")
|
|
280
|
+
text = content_text(response.content).strip()
|
|
281
|
+
if not text:
|
|
282
|
+
raise InitError("规则草稿是空文本,已放弃写入")
|
|
283
|
+
return InitDraft(text=text, usage=response.usage)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _object_mapping(value: object) -> dict[str, object] | None:
|
|
287
|
+
"""把 TOML / JSON 解析出来的表收窄成键为字符串的映射。"""
|
|
288
|
+
if not isinstance(value, dict):
|
|
289
|
+
return None
|
|
290
|
+
return cast(dict[str, object], value)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _read_text(path: Path, *, max_lines: int = 200) -> str:
|
|
294
|
+
try:
|
|
295
|
+
text = path.read_text(encoding="utf-8")
|
|
296
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
297
|
+
raise InitError(f"无法读取 {path}:{exc}") from exc
|
|
298
|
+
return "\n".join(text.splitlines()[:max_lines])
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
__all__ = [
|
|
302
|
+
"INIT_MAX_TOKENS",
|
|
303
|
+
"INIT_SYSTEM_PROMPT",
|
|
304
|
+
"INIT_TIMEOUT_SECONDS",
|
|
305
|
+
"InitDraft",
|
|
306
|
+
"InitError",
|
|
307
|
+
"RepoFacts",
|
|
308
|
+
"build_init_instruction",
|
|
309
|
+
"compose_draft",
|
|
310
|
+
"diff_lines",
|
|
311
|
+
"request_rules_draft",
|
|
312
|
+
"scan_repository",
|
|
313
|
+
]
|