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,149 @@
1
+ """结构化日志:统一字段、text/JSON 两种格式、stderr 单一出口。
2
+
3
+ 每条记录带六个字段:``session_id`` / ``run_id`` / ``turn_id`` / ``tool_call_id`` /
4
+ ``model`` / ``duration_ms``。缺失的字段写 null,消费方不需要判断"这个字段在不在"。
5
+ 所有文本先过 :class:`~braid_coding_agent.observability.redaction.Redactor`。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import sys
12
+ from collections.abc import Mapping
13
+ from typing import TextIO
14
+
15
+ from braid_ai.types import JsonValue
16
+ from braid_coding_agent.observability.redaction import Redactor
17
+ from braid_coding_agent.observability.settings import LOG_LEVELS, ObservabilitySettings
18
+
19
+ UNIFIED_FIELDS: tuple[str, ...] = (
20
+ "session_id",
21
+ "run_id",
22
+ "turn_id",
23
+ "tool_call_id",
24
+ "model",
25
+ "duration_ms",
26
+ )
27
+
28
+ _LEVEL_ORDER: dict[str, int] = {level: index for index, level in enumerate(LOG_LEVELS)}
29
+
30
+
31
+ def normalize_level(raw: str) -> str:
32
+ """把大小写混写的级别名收敛到白名单;未知值就地失败。"""
33
+ upper = raw.upper()
34
+ if upper not in _LEVEL_ORDER:
35
+ raise ValueError(f"未知的日志级别 {raw!r},可用: {', '.join(LOG_LEVELS)}")
36
+ return upper
37
+
38
+
39
+ class ObservabilityLogger:
40
+ """轻量日志器。不走 stdlib logging 的全局配置,避免影响其他库。"""
41
+
42
+ def __init__(
43
+ self,
44
+ settings: ObservabilitySettings,
45
+ *,
46
+ stream: TextIO | None = None,
47
+ redactor: Redactor | None = None,
48
+ ) -> None:
49
+ self._settings = settings
50
+ self._stream = stream if stream is not None else sys.stderr
51
+ self._redactor = redactor if redactor is not None else Redactor()
52
+ self._level = _LEVEL_ORDER[normalize_level(settings.log_level)]
53
+
54
+ @property
55
+ def stream(self) -> TextIO:
56
+ return self._stream
57
+
58
+ def logs_text(self) -> str:
59
+ """测试与 ``/status`` 用的快照接口。真实 stream 不会被改。"""
60
+ getvalue = getattr(self._stream, "getvalue", None)
61
+ if callable(getvalue):
62
+ result = getvalue()
63
+ return result if isinstance(result, str) else ""
64
+ return ""
65
+
66
+ def _enabled(self, level: str) -> bool:
67
+ return _LEVEL_ORDER[level] >= self._level
68
+
69
+ def _record(
70
+ self,
71
+ level: str,
72
+ event: str,
73
+ source: object,
74
+ message: str,
75
+ fields: Mapping[str, JsonValue | None],
76
+ ) -> None:
77
+ if not self._settings.enabled or not self._enabled(level):
78
+ return
79
+ unified: dict[str, JsonValue | None] = {field: None for field in UNIFIED_FIELDS}
80
+ for key, value in fields.items():
81
+ if key in unified:
82
+ unified[key] = value
83
+ payload: dict[str, JsonValue] = {
84
+ "timestampMs": int(getattr(source, "timestamp_ms", 0) or 0),
85
+ "level": level,
86
+ "event": event,
87
+ "message": self._redactor.redact_text(message),
88
+ }
89
+ for key, value in unified.items():
90
+ payload[key] = self._redactor.redact_value(value) if value is not None else None # type: ignore[assignment]
91
+ if self._settings.log_format == "json":
92
+ line = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
93
+ else:
94
+ suffix = " ".join(
95
+ f"{key}={value}" for key, value in unified.items() if value is not None
96
+ )
97
+ line = f"[{level}] {event} {payload['message']}" + (f" ({suffix})" if suffix else "")
98
+ self._stream.write(line + "\n")
99
+
100
+ def debug(
101
+ self,
102
+ event: str,
103
+ source: object,
104
+ *,
105
+ message: str = "",
106
+ **fields: JsonValue | None,
107
+ ) -> None:
108
+ self._record("DEBUG", event, source, message, fields)
109
+
110
+ def emit(
111
+ self,
112
+ event: str,
113
+ source: object,
114
+ *,
115
+ message: str = "",
116
+ level: str = "INFO",
117
+ **fields: JsonValue | None,
118
+ ) -> None:
119
+ self._record(level, event, source, message, fields)
120
+
121
+ def info(
122
+ self,
123
+ event: str,
124
+ source: object,
125
+ *,
126
+ message: str = "",
127
+ **fields: JsonValue | None,
128
+ ) -> None:
129
+ self._record("INFO", event, source, message, fields)
130
+
131
+ def warning(
132
+ self,
133
+ event: str,
134
+ source: object,
135
+ *,
136
+ message: str = "",
137
+ **fields: JsonValue | None,
138
+ ) -> None:
139
+ self._record("WARNING", event, source, message, fields)
140
+
141
+ def error(
142
+ self,
143
+ event: str,
144
+ source: object,
145
+ *,
146
+ message: str = "",
147
+ **fields: JsonValue | None,
148
+ ) -> None:
149
+ self._record("ERROR", event, source, message, fields)
@@ -0,0 +1,96 @@
1
+ """敏感信息过滤:观测输出里不记录 API Key、完整环境变量与凭证文件内容。
2
+
3
+ 三层策略,按开销从低到高:
4
+
5
+ 1. 已知秘密值:装配时收进来的凭证原文,逐字替换;
6
+ 2. 键名模式:``api_key`` / ``password`` / ``token`` / ``secret`` 一类键的值整体替换;
7
+ 3. 值形状:``sk-`` 开头的长串、PEM 私钥块、``Bearer <token>``。
8
+
9
+ 过滤只作用于写向 stderr 的日志与会话文件里的审计条目,绝不改发往模型的消息:
10
+ 工具参数要照原样交给执行层,观测层拿到的是同一份数据的副本。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from collections.abc import Iterable, Mapping
17
+
18
+ from braid_ai.types import JsonValue
19
+
20
+ REDACTED = "[REDACTED]"
21
+
22
+ #: 值形状。``sk-`` 覆盖 OpenAI / DeepSeek,``ghp_`` / ``github_pat_`` 覆盖 GitHub,
23
+ #: ``AKIA`` 覆盖 AWS;都是"看起来就像密钥"的高置信片段。
24
+ _SECRET_PATTERNS: tuple[re.Pattern[str], ...] = (
25
+ re.compile(r"\bsk-[A-Za-z0-9_-]{12,}"),
26
+ re.compile(r"\bghp_[A-Za-z0-9]{20,}"),
27
+ re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}"),
28
+ re.compile(r"\bAKIA[A-Z0-9]{16}\b"),
29
+ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----"),
30
+ re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{12,}"),
31
+ )
32
+
33
+ #: 键名里出现这些片段就整体替换值,避免"我知道值长什么样"之外的泄漏。
34
+ _SENSITIVE_KEY_PARTS: tuple[str, ...] = (
35
+ "api_key",
36
+ "apikey",
37
+ "token",
38
+ "secret",
39
+ "password",
40
+ "passwd",
41
+ "credential",
42
+ "authorization",
43
+ "private_key",
44
+ "access_key",
45
+ )
46
+
47
+
48
+ def _is_sensitive_key(key: str) -> bool:
49
+ lowered = key.lower()
50
+ return any(part in lowered for part in _SENSITIVE_KEY_PARTS)
51
+
52
+
53
+ class Redactor:
54
+ """一份秘密清单 + 一组形状规则。构造一次,日志与审计共用。"""
55
+
56
+ def __init__(self, secrets: Iterable[str] = ()) -> None:
57
+ self._secrets: tuple[str, ...] = tuple(
58
+ sorted(
59
+ (secret for secret in secrets if secret),
60
+ key=len,
61
+ reverse=True,
62
+ )
63
+ )
64
+
65
+ def add(self, secret: str) -> None:
66
+ """追加一个已知秘密值。重复值不影响结果。"""
67
+ if secret and secret not in self._secrets:
68
+ self._secrets = (*self._secrets, secret)
69
+
70
+ def redact_text(self, text: str) -> str:
71
+ """按已知值与形状规则替换文本里的秘密片段。"""
72
+ cleaned = text
73
+ for secret in self._secrets:
74
+ if secret in cleaned:
75
+ cleaned = cleaned.replace(secret, REDACTED)
76
+ for pattern in _SECRET_PATTERNS:
77
+ cleaned = pattern.sub(REDACTED, cleaned)
78
+ return cleaned
79
+
80
+ def redact_value(self, value: JsonValue) -> JsonValue:
81
+ """递归处理 JSON 值:敏感键整体替换,字符串走文本规则。"""
82
+ if isinstance(value, str):
83
+ return self.redact_text(value)
84
+ if isinstance(value, Mapping):
85
+ return {
86
+ key: (REDACTED if _is_sensitive_key(key) else self.redact_value(item))
87
+ for key, item in value.items()
88
+ }
89
+ if isinstance(value, list):
90
+ return [self.redact_value(item) for item in value]
91
+ return value
92
+
93
+
94
+ def redact_mapping(value: Mapping[str, JsonValue], *, secrets: Iterable[str] = ()) -> JsonValue:
95
+ """一次性构造过滤器并处理一个映射。给不想持有 :class:`Redactor` 的调用方用。"""
96
+ return Redactor(secrets).redact_value(dict(value))
@@ -0,0 +1,29 @@
1
+ """可观测性配置形状。
2
+
3
+ ``enabled`` 控制 span/审计采集;``log_level`` 与 ``log_format`` 控制结构化日志;
4
+ ``otel_enabled`` 是 OpenTelemetry 导出开关,默认关闭——观测不能悄悄把数据发到外部。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from typing import Literal
11
+
12
+ type LogFormat = Literal["text", "json"]
13
+ type LogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
14
+
15
+ LOG_LEVELS: tuple[str, ...] = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")
16
+ LOG_FORMATS: tuple[str, ...] = ("text", "json")
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class ObservabilitySettings:
21
+ """一份合并完成的可观测性配置。"""
22
+
23
+ enabled: bool = True
24
+ log_level: str = "WARNING"
25
+ log_format: LogFormat = "text"
26
+ #: OpenTelemetry 风格的导出器开关。默认关闭,开启时需要调用方提供 exporter。
27
+ otel_enabled: bool = False
28
+ #: 可选:把每次运行的 span 树写成 JSONL。空表示不落盘。
29
+ export_jsonl: str = ""
@@ -0,0 +1,239 @@
1
+ """Span 树:把会话事件流折成一棵可导出的树。
2
+
3
+ 四个 kind 对应四种代价:
4
+
5
+ - ``run``:一次用户输入到 ``agent_settled`` 的整段;
6
+ - ``turn``:一次模型请求加它引发的工具批次;
7
+ - ``model``:一次模型请求,带 usage、模型名与耗时;
8
+ - ``tool``:一次工具执行,带 tool_call_id、耗时与成败。
9
+
10
+ 事件顺序沿用 ``braid_agent.types`` 的契约;收集器是只读订阅者,不改内核状态。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import uuid
16
+ from dataclasses import dataclass, field
17
+ from typing import Literal
18
+
19
+ from braid_ai.types import AssistantMessage, JsonValue, Usage
20
+
21
+ type SpanKind = Literal["run", "turn", "model", "tool"]
22
+ type SpanStatus = Literal["ok", "error", "unset"]
23
+
24
+
25
+ def new_id() -> str:
26
+ return uuid.uuid4().hex[:16]
27
+
28
+
29
+ def usage_to_wire(usage: Usage) -> dict[str, JsonValue]:
30
+ """用量汇总的 wire 形状,与会话文件里的 message.usage 用同一套键。"""
31
+ return {
32
+ "input": usage.input,
33
+ "output": usage.output,
34
+ "cacheRead": usage.cache_read,
35
+ "cacheWrite": usage.cache_write,
36
+ "totalTokens": usage.total_tokens,
37
+ "costTotal": usage.cost.total,
38
+ }
39
+
40
+
41
+ @dataclass(slots=True)
42
+ class Span:
43
+ """一个时间区间。字段对齐 OpenTelemetry 的 span 语义,但不依赖其 SDK。"""
44
+
45
+ name: str
46
+ kind: SpanKind
47
+ trace_id: str
48
+ span_id: str = field(default_factory=new_id)
49
+ parent_span_id: str | None = None
50
+ start_ms: int = 0
51
+ duration_ms: int | None = None
52
+ status: SpanStatus = "unset"
53
+ tool_call_id: str | None = None
54
+ model: str | None = None
55
+ usage: Usage | None = None
56
+ attributes: dict[str, JsonValue] = field(default_factory=dict[str, JsonValue])
57
+
58
+ def to_wire(self) -> dict[str, JsonValue]:
59
+ payload: dict[str, JsonValue] = {
60
+ "spanId": self.span_id,
61
+ "parentSpanId": self.parent_span_id,
62
+ "traceId": self.trace_id,
63
+ "name": self.name,
64
+ "kind": self.kind,
65
+ "startMs": self.start_ms,
66
+ "durationMs": self.duration_ms,
67
+ "status": self.status,
68
+ "attributes": self.attributes,
69
+ }
70
+ if self.tool_call_id is not None:
71
+ payload["toolCallId"] = self.tool_call_id
72
+ if self.model is not None:
73
+ payload["model"] = self.model
74
+ if self.usage is not None:
75
+ payload["usage"] = usage_to_wire(self.usage)
76
+ return payload
77
+
78
+
79
+ @dataclass(slots=True)
80
+ class SpanTree:
81
+ """一次 run 的完整轨迹。``root`` 也在 ``spans`` 里。"""
82
+
83
+ session_id: str
84
+ run_id: str
85
+ trace_id: str
86
+ spans: list[Span] = field(default_factory=list[Span])
87
+ root: Span | None = None
88
+
89
+ def to_wire(self) -> dict[str, JsonValue]:
90
+ return {
91
+ "sessionId": self.session_id,
92
+ "runId": self.run_id,
93
+ "traceId": self.trace_id,
94
+ "spans": [span.to_wire() for span in self.spans],
95
+ }
96
+
97
+
98
+ class SpanTreeBuilder:
99
+ """把 ``SessionEvent`` 转成 span。用事件上的 ``type`` 分派,避免反向依赖会话层。"""
100
+
101
+ def __init__(
102
+ self,
103
+ session_id: str,
104
+ run_id: str,
105
+ *,
106
+ trace_id: str | None = None,
107
+ clock_ms: int = 0,
108
+ ) -> None:
109
+ self._session_id = session_id
110
+ self._run_id = run_id
111
+ self._trace_id = trace_id or new_id()
112
+ self._clock_ms = clock_ms
113
+ self._spans: list[Span] = []
114
+ self._root: Span | None = None
115
+ self._stack: list[Span] = []
116
+ self._tools: dict[str, Span] = {}
117
+ self._model_spans: dict[int, Span] = {}
118
+ self._turn_models: dict[str, Span] = {}
119
+ self._current_turn: Span | None = None
120
+ self._model_index: int = 0
121
+
122
+ @property
123
+ def trace_id(self) -> str:
124
+ return self._trace_id
125
+
126
+ def _add(self, span: Span) -> Span:
127
+ self._spans.append(span)
128
+ return span
129
+
130
+ def _top(self) -> Span | None:
131
+ return self._stack[-1] if self._stack else self._root
132
+
133
+ def on_event(self, event: object) -> None:
134
+ kind: str = getattr(event, "type", "")
135
+ if kind == "agent_start":
136
+ if self._root is None:
137
+ self._root = self._add(
138
+ Span(
139
+ name="agent.run",
140
+ kind="run",
141
+ trace_id=self._trace_id,
142
+ parent_span_id=None,
143
+ start_ms=self._clock_ms,
144
+ status="unset",
145
+ )
146
+ )
147
+ self._stack.append(self._root)
148
+ return
149
+ if kind == "turn_start":
150
+ turn = self._add(
151
+ Span(
152
+ name="agent.turn",
153
+ kind="turn",
154
+ trace_id=self._trace_id,
155
+ parent_span_id=self._root.span_id if self._root else None,
156
+ start_ms=self._clock_ms,
157
+ )
158
+ )
159
+ self._current_turn = turn
160
+ self._stack.append(turn)
161
+ return
162
+ if kind == "tool_execution_start":
163
+ tool_call_id = str(getattr(event, "tool_call_id", ""))
164
+ parent = self._top()
165
+ span = self._add(
166
+ Span(
167
+ name=f"tool.{getattr(event, 'tool_name', 'unknown')}",
168
+ kind="tool",
169
+ trace_id=self._trace_id,
170
+ parent_span_id=parent.span_id if parent is not None else None,
171
+ start_ms=self._clock_ms,
172
+ tool_call_id=tool_call_id,
173
+ )
174
+ )
175
+ self._tools[tool_call_id] = span
176
+ return
177
+ if kind == "tool_execution_end":
178
+ tool_call_id = str(getattr(event, "tool_call_id", ""))
179
+ span = self._tools.get(tool_call_id)
180
+ if span is not None:
181
+ span.duration_ms = int(getattr(event, "duration_ms", 0) or 0)
182
+ span.status = "error" if getattr(event, "is_error", False) else "ok"
183
+ return
184
+ if kind == "message_end":
185
+ message = getattr(event, "message", None)
186
+ if isinstance(message, AssistantMessage):
187
+ model_name = (
188
+ f"{message.provider}/{message.model}" if message.model else message.provider
189
+ )
190
+ span = self._add(
191
+ Span(
192
+ name="model.request",
193
+ kind="model",
194
+ trace_id=self._trace_id,
195
+ parent_span_id=self._current_turn.span_id if self._current_turn else None,
196
+ start_ms=self._clock_ms,
197
+ model=model_name,
198
+ usage=message.usage,
199
+ duration_ms=message.duration_ms,
200
+ status="error" if message.stop_reason == "error" else "ok",
201
+ )
202
+ )
203
+ self._model_spans[self._model_index] = span
204
+ self._model_index += 1
205
+ return
206
+ if kind == "turn_end":
207
+ if self._stack and self._stack[-1].kind == "turn":
208
+ self._stack.pop()
209
+ self._current_turn = None
210
+ return
211
+ if kind in ("agent_end", "agent_settled"):
212
+ while len(self._stack) > 1:
213
+ self._stack.pop()
214
+ if self._root is not None:
215
+ self._root.duration_ms = max(self._clock_ms - self._root.start_ms, 0)
216
+ self._root.status = (
217
+ "error"
218
+ if kind == "agent_end" and getattr(event, "messages", []) and self._any_error()
219
+ else "ok"
220
+ )
221
+ return
222
+
223
+ def _any_error(self) -> bool:
224
+ return any(span.status == "error" for span in self._spans)
225
+
226
+ def finish(self) -> SpanTree:
227
+ """收口:未关闭的 span 按当前时钟补一个长度,确保树里没有半截数据。"""
228
+ for span in self._spans:
229
+ if span.duration_ms is None:
230
+ span.duration_ms = max(self._clock_ms - span.start_ms, 0)
231
+ if self._root is not None and self._root.duration_ms is None:
232
+ self._root.duration_ms = max(self._clock_ms - self._root.start_ms, 0)
233
+ return SpanTree(
234
+ session_id=self._session_id,
235
+ run_id=self._run_id,
236
+ trace_id=self._trace_id,
237
+ spans=list(self._spans),
238
+ root=self._root,
239
+ )
@@ -0,0 +1,185 @@
1
+ """工具执行前的权限判定、运行模式与 ``/permission`` 命令。
2
+
3
+ :mod:`braid_coding_agent.permissions.engine` 是运行时入口;纯判定在
4
+ :mod:`braid_coding_agent.permissions.evaluate`,规则文件与项目信任在
5
+ :mod:`braid_coding_agent.permissions.store`。REPL、TUI、RPC 与 HTTP 都从这一层取
6
+ 结论,不各自再读一遍规则文件。
7
+ """
8
+
9
+ import importlib
10
+ from typing import TYPE_CHECKING
11
+
12
+ if TYPE_CHECKING:
13
+ from braid_coding_agent.permissions.command import (
14
+ PermissionCommand,
15
+ PermissionCommandError,
16
+ PermissionCommandResult,
17
+ execute_permission_command,
18
+ parse_permission_command,
19
+ )
20
+ from braid_coding_agent.permissions.engine import (
21
+ APPROVAL_SCOPES,
22
+ BUILTIN_BASH_RULES,
23
+ BUILTIN_PATH_RULES,
24
+ DEFAULT_APPROVAL_TIMEOUT_SECONDS,
25
+ NETWORK_TOOLS,
26
+ PERMISSION_ACTIONS,
27
+ PERMISSION_MODES,
28
+ PLAN_FILE_NAMES,
29
+ PLAN_TOOLS,
30
+ READ_ONLY_TOOLS,
31
+ RULE_SCOPES,
32
+ RULE_TABLES,
33
+ SHELL_TOOLS,
34
+ WRITE_TOOLS,
35
+ ApprovalAnswer,
36
+ ApprovalHandler,
37
+ ApprovalScope,
38
+ PermissionAction,
39
+ PermissionContext,
40
+ PermissionDecision,
41
+ PermissionEngine,
42
+ PermissionMode,
43
+ PermissionPrompt,
44
+ PermissionRequest,
45
+ PermissionSettings,
46
+ RuleProposal,
47
+ RuleScope,
48
+ RuleSet,
49
+ ScopedRule,
50
+ build_request,
51
+ evaluate_rules,
52
+ proposal_for,
53
+ )
54
+ from braid_coding_agent.permissions.evaluate import compile_ruleset, evaluate
55
+ from braid_coding_agent.permissions.policy import mode_default, mode_label
56
+ from braid_coding_agent.permissions.store import (
57
+ PermissionStore,
58
+ PermissionStoreError,
59
+ RuleFile,
60
+ TrustRecord,
61
+ load_rule_file,
62
+ load_trust,
63
+ save_trust,
64
+ write_rule_file,
65
+ )
66
+
67
+ _LAZY_ENGINE: tuple[str, ...] = (
68
+ "APPROVAL_SCOPES",
69
+ "BUILTIN_BASH_RULES",
70
+ "BUILTIN_PATH_RULES",
71
+ "DEFAULT_APPROVAL_TIMEOUT_SECONDS",
72
+ "NETWORK_TOOLS",
73
+ "PERMISSION_ACTIONS",
74
+ "PERMISSION_MODES",
75
+ "PLAN_FILE_NAMES",
76
+ "PLAN_TOOLS",
77
+ "READ_ONLY_TOOLS",
78
+ "RULE_SCOPES",
79
+ "RULE_TABLES",
80
+ "SHELL_TOOLS",
81
+ "WRITE_TOOLS",
82
+ "ApprovalAnswer",
83
+ "ApprovalHandler",
84
+ "ApprovalScope",
85
+ "PermissionAction",
86
+ "PermissionContext",
87
+ "PermissionDecision",
88
+ "PermissionEngine",
89
+ "PermissionMode",
90
+ "PermissionPrompt",
91
+ "PermissionRequest",
92
+ "PermissionSettings",
93
+ "RuleProposal",
94
+ "RuleScope",
95
+ "RuleSet",
96
+ "ScopedRule",
97
+ "build_request",
98
+ "evaluate_rules",
99
+ "proposal_for",
100
+ )
101
+
102
+ #: 导出名 → 定义它的模块。命令层与运行时权限引擎在首次使用时才加载。
103
+ _LAZY_EXPORTS: dict[str, str] = {
104
+ **{name: "braid_coding_agent.permissions.engine" for name in _LAZY_ENGINE},
105
+ "PermissionCommand": "braid_coding_agent.permissions.command",
106
+ "PermissionCommandError": "braid_coding_agent.permissions.command",
107
+ "PermissionCommandResult": "braid_coding_agent.permissions.command",
108
+ "execute_permission_command": "braid_coding_agent.permissions.command",
109
+ "parse_permission_command": "braid_coding_agent.permissions.command",
110
+ "compile_ruleset": "braid_coding_agent.permissions.evaluate",
111
+ "evaluate": "braid_coding_agent.permissions.evaluate",
112
+ "mode_default": "braid_coding_agent.permissions.policy",
113
+ "mode_label": "braid_coding_agent.permissions.policy",
114
+ "PermissionStore": "braid_coding_agent.permissions.store",
115
+ "PermissionStoreError": "braid_coding_agent.permissions.store",
116
+ "RuleFile": "braid_coding_agent.permissions.store",
117
+ "TrustRecord": "braid_coding_agent.permissions.store",
118
+ "load_rule_file": "braid_coding_agent.permissions.store",
119
+ "load_trust": "braid_coding_agent.permissions.store",
120
+ "save_trust": "braid_coding_agent.permissions.store",
121
+ "write_rule_file": "braid_coding_agent.permissions.store",
122
+ }
123
+
124
+
125
+ def __getattr__(name: str) -> object:
126
+ """按需导入导出名。"""
127
+ module_name = _LAZY_EXPORTS.get(name)
128
+ if module_name is None:
129
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
130
+ value = getattr(importlib.import_module(module_name), name)
131
+ globals()[name] = value
132
+ return value
133
+
134
+
135
+ __all__ = [
136
+ "APPROVAL_SCOPES",
137
+ "BUILTIN_BASH_RULES",
138
+ "BUILTIN_PATH_RULES",
139
+ "DEFAULT_APPROVAL_TIMEOUT_SECONDS",
140
+ "NETWORK_TOOLS",
141
+ "PERMISSION_ACTIONS",
142
+ "PERMISSION_MODES",
143
+ "PLAN_FILE_NAMES",
144
+ "PLAN_TOOLS",
145
+ "READ_ONLY_TOOLS",
146
+ "RULE_SCOPES",
147
+ "RULE_TABLES",
148
+ "SHELL_TOOLS",
149
+ "WRITE_TOOLS",
150
+ "ApprovalAnswer",
151
+ "ApprovalHandler",
152
+ "ApprovalScope",
153
+ "PermissionAction",
154
+ "PermissionCommand",
155
+ "PermissionCommandError",
156
+ "PermissionCommandResult",
157
+ "PermissionContext",
158
+ "PermissionDecision",
159
+ "PermissionEngine",
160
+ "PermissionMode",
161
+ "PermissionPrompt",
162
+ "PermissionRequest",
163
+ "PermissionSettings",
164
+ "PermissionStore",
165
+ "PermissionStoreError",
166
+ "RuleFile",
167
+ "RuleProposal",
168
+ "RuleScope",
169
+ "RuleSet",
170
+ "ScopedRule",
171
+ "TrustRecord",
172
+ "build_request",
173
+ "compile_ruleset",
174
+ "evaluate",
175
+ "evaluate_rules",
176
+ "execute_permission_command",
177
+ "load_rule_file",
178
+ "load_trust",
179
+ "mode_default",
180
+ "mode_label",
181
+ "parse_permission_command",
182
+ "proposal_for",
183
+ "save_trust",
184
+ "write_rule_file",
185
+ ]