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,101 @@
|
|
|
1
|
+
"""可观测性与审计:把一次运行回答成"看到了什么、调用了什么、谁批准了什么、花了多少"。
|
|
2
|
+
|
|
3
|
+
四个子模块各自独立,组合点在外层:
|
|
4
|
+
|
|
5
|
+
- :mod:`settings` 是配置形状,默认关闭 OpenTelemetry 导出;
|
|
6
|
+
- :mod:`redaction` 过滤日志与审计里的凭证,是安全边界;
|
|
7
|
+
- :mod:`spans` 把会话事件折成 span 树;
|
|
8
|
+
- :mod:`audit` 记录权限决策;
|
|
9
|
+
- :mod:`exporter` 定义导出接口,默认 noop;
|
|
10
|
+
- :mod:`logging_setup` 把统一字段写进 stderr 的 text/JSON 日志;
|
|
11
|
+
- :mod:`collector` 把上面几块接到 ``AgentSession``。
|
|
12
|
+
|
|
13
|
+
输出只走 stderr:stdout 由 print / json / rpc 通道占着,日志混进去会破坏协议。
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import importlib
|
|
17
|
+
from typing import TYPE_CHECKING
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from braid_coding_agent.observability.audit import (
|
|
21
|
+
AuditLog,
|
|
22
|
+
AuditRecord,
|
|
23
|
+
permission_audit,
|
|
24
|
+
)
|
|
25
|
+
from braid_coding_agent.observability.collector import (
|
|
26
|
+
ObservabilityCollector,
|
|
27
|
+
ObservabilityStatus,
|
|
28
|
+
)
|
|
29
|
+
from braid_coding_agent.observability.exporter import (
|
|
30
|
+
InMemorySpanExporter,
|
|
31
|
+
JsonFileSpanExporter,
|
|
32
|
+
NoopSpanExporter,
|
|
33
|
+
SpanExporter,
|
|
34
|
+
)
|
|
35
|
+
from braid_coding_agent.observability.logging_setup import (
|
|
36
|
+
ObservabilityLogger,
|
|
37
|
+
normalize_level,
|
|
38
|
+
)
|
|
39
|
+
from braid_coding_agent.observability.redaction import Redactor, redact_mapping
|
|
40
|
+
from braid_coding_agent.observability.settings import (
|
|
41
|
+
LOG_FORMATS,
|
|
42
|
+
LOG_LEVELS,
|
|
43
|
+
ObservabilitySettings,
|
|
44
|
+
)
|
|
45
|
+
from braid_coding_agent.observability.spans import Span, SpanTree, SpanTreeBuilder
|
|
46
|
+
|
|
47
|
+
_LAZY_EXPORTS: dict[str, str] = {
|
|
48
|
+
"AuditLog": "braid_coding_agent.observability.audit",
|
|
49
|
+
"AuditRecord": "braid_coding_agent.observability.audit",
|
|
50
|
+
"permission_audit": "braid_coding_agent.observability.audit",
|
|
51
|
+
"ObservabilityCollector": "braid_coding_agent.observability.collector",
|
|
52
|
+
"ObservabilityStatus": "braid_coding_agent.observability.collector",
|
|
53
|
+
"InMemorySpanExporter": "braid_coding_agent.observability.exporter",
|
|
54
|
+
"JsonFileSpanExporter": "braid_coding_agent.observability.exporter",
|
|
55
|
+
"NoopSpanExporter": "braid_coding_agent.observability.exporter",
|
|
56
|
+
"SpanExporter": "braid_coding_agent.observability.exporter",
|
|
57
|
+
"ObservabilityLogger": "braid_coding_agent.observability.logging_setup",
|
|
58
|
+
"normalize_level": "braid_coding_agent.observability.logging_setup",
|
|
59
|
+
"Redactor": "braid_coding_agent.observability.redaction",
|
|
60
|
+
"redact_mapping": "braid_coding_agent.observability.redaction",
|
|
61
|
+
"LOG_FORMATS": "braid_coding_agent.observability.settings",
|
|
62
|
+
"LOG_LEVELS": "braid_coding_agent.observability.settings",
|
|
63
|
+
"ObservabilitySettings": "braid_coding_agent.observability.settings",
|
|
64
|
+
"Span": "braid_coding_agent.observability.spans",
|
|
65
|
+
"SpanTree": "braid_coding_agent.observability.spans",
|
|
66
|
+
"SpanTreeBuilder": "braid_coding_agent.observability.spans",
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def __getattr__(name: str) -> object:
|
|
71
|
+
"""按需导入导出名。"""
|
|
72
|
+
module_name = _LAZY_EXPORTS.get(name)
|
|
73
|
+
if module_name is None:
|
|
74
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
75
|
+
module = importlib.import_module(module_name)
|
|
76
|
+
value = getattr(module, name)
|
|
77
|
+
globals()[name] = value
|
|
78
|
+
return value
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
__all__ = [
|
|
82
|
+
"LOG_FORMATS",
|
|
83
|
+
"LOG_LEVELS",
|
|
84
|
+
"AuditLog",
|
|
85
|
+
"AuditRecord",
|
|
86
|
+
"InMemorySpanExporter",
|
|
87
|
+
"JsonFileSpanExporter",
|
|
88
|
+
"NoopSpanExporter",
|
|
89
|
+
"ObservabilityCollector",
|
|
90
|
+
"ObservabilityLogger",
|
|
91
|
+
"ObservabilitySettings",
|
|
92
|
+
"ObservabilityStatus",
|
|
93
|
+
"Redactor",
|
|
94
|
+
"Span",
|
|
95
|
+
"SpanExporter",
|
|
96
|
+
"SpanTree",
|
|
97
|
+
"SpanTreeBuilder",
|
|
98
|
+
"normalize_level",
|
|
99
|
+
"permission_audit",
|
|
100
|
+
"redact_mapping",
|
|
101
|
+
]
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""审计:权限决策的独立记录。
|
|
2
|
+
|
|
3
|
+
权限引擎只负责判定,这里只负责留痕;两者通过 :func:`permission_audit` 的显式调用连接。
|
|
4
|
+
记录内容回答四个问题:哪条规则命中、动了哪些路径、谁在哪个范围批准、为什么拒绝。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections import deque
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import ClassVar, Literal
|
|
12
|
+
|
|
13
|
+
from braid_ai.types import JsonValue
|
|
14
|
+
from braid_coding_agent.observability.redaction import Redactor
|
|
15
|
+
from braid_coding_agent.permissions.engine import (
|
|
16
|
+
ApprovalScope,
|
|
17
|
+
PermissionAction,
|
|
18
|
+
PermissionDecision,
|
|
19
|
+
PermissionRequest,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
type AuditKind = Literal["permission_decision"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class AuditRecord:
|
|
27
|
+
"""一条审计记录。字段是扁平的,方便直接写成 JSONL。"""
|
|
28
|
+
|
|
29
|
+
kind: AuditKind
|
|
30
|
+
session_id: str
|
|
31
|
+
run_id: str
|
|
32
|
+
tool_name: str
|
|
33
|
+
tool_call_id: str
|
|
34
|
+
action: PermissionAction
|
|
35
|
+
rule: str
|
|
36
|
+
reason: str
|
|
37
|
+
paths: tuple[str, ...] = ()
|
|
38
|
+
command: str | None = None
|
|
39
|
+
host: str | None = None
|
|
40
|
+
scope: ApprovalScope | None = None
|
|
41
|
+
approver: str = "policy"
|
|
42
|
+
timestamp_ms: int = 0
|
|
43
|
+
type: ClassVar[str] = "permission_decision"
|
|
44
|
+
|
|
45
|
+
def to_wire(self) -> dict[str, JsonValue]:
|
|
46
|
+
payload: dict[str, JsonValue] = {
|
|
47
|
+
"type": "permission_decision",
|
|
48
|
+
"sessionId": self.session_id,
|
|
49
|
+
"runId": self.run_id,
|
|
50
|
+
"toolName": self.tool_name,
|
|
51
|
+
"toolCallId": self.tool_call_id,
|
|
52
|
+
"action": self.action,
|
|
53
|
+
"rule": self.rule,
|
|
54
|
+
"reason": self.reason,
|
|
55
|
+
"paths": list(self.paths),
|
|
56
|
+
"approver": self.approver,
|
|
57
|
+
"timestampMs": self.timestamp_ms,
|
|
58
|
+
}
|
|
59
|
+
if self.command is not None:
|
|
60
|
+
payload["command"] = self.command
|
|
61
|
+
if self.host is not None:
|
|
62
|
+
payload["host"] = self.host
|
|
63
|
+
if self.scope is not None:
|
|
64
|
+
payload["scope"] = self.scope
|
|
65
|
+
return payload
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def permission_audit(
|
|
69
|
+
decision: PermissionDecision,
|
|
70
|
+
request: PermissionRequest,
|
|
71
|
+
*,
|
|
72
|
+
session_id: str,
|
|
73
|
+
run_id: str,
|
|
74
|
+
scope: ApprovalScope | None = None,
|
|
75
|
+
approver: str | None = None,
|
|
76
|
+
timestamp_ms: int = 0,
|
|
77
|
+
redactor: Redactor | None = None,
|
|
78
|
+
) -> AuditRecord:
|
|
79
|
+
"""从判定与请求里抽出最小充分信息,不把完整工具参数写进审计。"""
|
|
80
|
+
filter_ = redactor if redactor is not None else Redactor()
|
|
81
|
+
resolved_scope = scope if scope is not None else decision.scope
|
|
82
|
+
if approver is not None:
|
|
83
|
+
source = approver
|
|
84
|
+
elif decision.rule.startswith("approval:") or decision.rule.startswith("session:"):
|
|
85
|
+
source = "user"
|
|
86
|
+
else:
|
|
87
|
+
source = "policy"
|
|
88
|
+
return AuditRecord(
|
|
89
|
+
kind="permission_decision",
|
|
90
|
+
session_id=session_id,
|
|
91
|
+
run_id=run_id,
|
|
92
|
+
tool_name=decision.tool_name,
|
|
93
|
+
tool_call_id=decision.tool_call_id,
|
|
94
|
+
action=decision.action,
|
|
95
|
+
rule=filter_.redact_text(decision.rule),
|
|
96
|
+
reason=filter_.redact_text(decision.reason),
|
|
97
|
+
paths=tuple(str(filter_.redact_text(path)) for path in request.paths),
|
|
98
|
+
command=filter_.redact_text(request.command) if request.command is not None else None,
|
|
99
|
+
host=request.host,
|
|
100
|
+
scope=resolved_scope,
|
|
101
|
+
approver=source,
|
|
102
|
+
timestamp_ms=timestamp_ms,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class AuditLog:
|
|
107
|
+
"""有界的审计环形缓冲。``/status`` 从这里读最近错误,不读会话文件。"""
|
|
108
|
+
|
|
109
|
+
def __init__(self, max_records: int = 200) -> None:
|
|
110
|
+
self._records: deque[AuditRecord] = deque(maxlen=max_records)
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def records(self) -> tuple[AuditRecord, ...]:
|
|
114
|
+
return tuple(self._records)
|
|
115
|
+
|
|
116
|
+
def append(self, record: AuditRecord) -> None:
|
|
117
|
+
self._records.append(record)
|
|
118
|
+
|
|
119
|
+
def recent_errors(self, limit: int = 20) -> tuple[AuditRecord, ...]:
|
|
120
|
+
denied = [record for record in self._records if record.action == "deny"]
|
|
121
|
+
return tuple(denied[-limit:])
|
|
122
|
+
|
|
123
|
+
def clear(self) -> None:
|
|
124
|
+
self._records.clear()
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""观测收集器:把会话事件、权限判定与使用量汇到一处。
|
|
2
|
+
|
|
3
|
+
生命周期刻意显式:装配时构造,``prompt()`` 开始时 ``begin_run``,``agent_settled``
|
|
4
|
+
之后 ``finish_run``。显式边界让"一次 run"与用户的一次输入对齐,也与 trace id 对齐;
|
|
5
|
+
事件本身没有 run_id 字段,靠边界注入比在每个事件上补 id 简单。
|
|
6
|
+
|
|
7
|
+
收集器是只读的:它订阅会话事件、接收权限审计回调,不参与决策,也不改发往模型的消息。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import uuid
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import TYPE_CHECKING
|
|
15
|
+
|
|
16
|
+
from braid_ai.types import JsonValue, Usage
|
|
17
|
+
from braid_ai.utils.clock import Clock
|
|
18
|
+
from braid_coding_agent.observability.audit import AuditLog, AuditRecord, permission_audit
|
|
19
|
+
from braid_coding_agent.observability.exporter import NoopSpanExporter, SpanExporter
|
|
20
|
+
from braid_coding_agent.observability.logging_setup import ObservabilityLogger
|
|
21
|
+
from braid_coding_agent.observability.redaction import Redactor
|
|
22
|
+
from braid_coding_agent.observability.settings import ObservabilitySettings
|
|
23
|
+
from braid_coding_agent.observability.spans import SpanTree, SpanTreeBuilder, usage_to_wire
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
from braid_coding_agent.permissions.engine import (
|
|
27
|
+
ApprovalScope,
|
|
28
|
+
PermissionDecision,
|
|
29
|
+
PermissionRequest,
|
|
30
|
+
)
|
|
31
|
+
from braid_coding_agent.session.manager import SessionManager
|
|
32
|
+
from braid_coding_agent.session.status import SessionTotals
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True, slots=True)
|
|
36
|
+
class ObservabilityStatus:
|
|
37
|
+
"""``/status`` 展示的当前运行快照。"""
|
|
38
|
+
|
|
39
|
+
trace_id: str | None = None
|
|
40
|
+
run_id: str | None = None
|
|
41
|
+
session_id: str | None = None
|
|
42
|
+
span_count: int = 0
|
|
43
|
+
recent_error_count: int = 0
|
|
44
|
+
|
|
45
|
+
def to_wire(self) -> dict[str, JsonValue]:
|
|
46
|
+
return {
|
|
47
|
+
"traceId": self.trace_id,
|
|
48
|
+
"runId": self.run_id,
|
|
49
|
+
"sessionId": self.session_id,
|
|
50
|
+
"spanCount": self.span_count,
|
|
51
|
+
"recentErrorCount": self.recent_error_count,
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(slots=True)
|
|
56
|
+
class _Source:
|
|
57
|
+
"""给日志器提供时间戳的默认源。"""
|
|
58
|
+
|
|
59
|
+
timestamp_ms: int = 0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ObservabilityCollector:
|
|
63
|
+
"""一次进程一份;每次 run 重置内部的 span 树与用量账本。"""
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
*,
|
|
68
|
+
settings: ObservabilitySettings,
|
|
69
|
+
clock: Clock,
|
|
70
|
+
redactor: Redactor | None = None,
|
|
71
|
+
exporter: SpanExporter | None = None,
|
|
72
|
+
session: SessionManager | None = None,
|
|
73
|
+
) -> None:
|
|
74
|
+
self._settings = settings
|
|
75
|
+
self._clock = clock
|
|
76
|
+
self._redactor = redactor if redactor is not None else Redactor()
|
|
77
|
+
self._exporter = exporter if exporter is not None else NoopSpanExporter()
|
|
78
|
+
self._session = session
|
|
79
|
+
self._logger = ObservabilityLogger(settings, redactor=self._redactor)
|
|
80
|
+
self._audit = AuditLog()
|
|
81
|
+
self._status = ObservabilityStatus()
|
|
82
|
+
self._builder: SpanTreeBuilder | None = None
|
|
83
|
+
self._usage = Usage()
|
|
84
|
+
self._session_id = ""
|
|
85
|
+
self._run_id = ""
|
|
86
|
+
self._model = ""
|
|
87
|
+
self._run_audits: list[AuditRecord] = []
|
|
88
|
+
self._last_tree: SpanTree | None = None
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def audit(self) -> AuditLog:
|
|
92
|
+
return self._audit
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def exporter(self) -> SpanExporter:
|
|
96
|
+
return self._exporter
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def logger(self) -> ObservabilityLogger:
|
|
100
|
+
return self._logger
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def model(self) -> str:
|
|
104
|
+
return self._model
|
|
105
|
+
|
|
106
|
+
def logs_text(self) -> str:
|
|
107
|
+
return self._logger.logs_text()
|
|
108
|
+
|
|
109
|
+
def usage_summary(self) -> dict[str, JsonValue]:
|
|
110
|
+
"""本次 run 的用量汇总。与写进会话文件的数据是同一个来源。"""
|
|
111
|
+
return dict(usage_to_wire(self._usage))
|
|
112
|
+
|
|
113
|
+
def status(self) -> ObservabilityStatus:
|
|
114
|
+
return self._status
|
|
115
|
+
|
|
116
|
+
# ------------------------------------------------------------------ 运行边界
|
|
117
|
+
|
|
118
|
+
def begin_run(self, *, session_id: str, model: str, run_id: str | None = None) -> str:
|
|
119
|
+
"""一次用户输入开始时调用。返回的 run_id 会写进日志与会话条目。"""
|
|
120
|
+
self._session_id = session_id
|
|
121
|
+
self._model = model
|
|
122
|
+
self._run_id = run_id or uuid.uuid4().hex[:16]
|
|
123
|
+
self._usage = Usage()
|
|
124
|
+
self._run_audits = []
|
|
125
|
+
self._last_tree = None
|
|
126
|
+
self._status = ObservabilityStatus(
|
|
127
|
+
trace_id=self._builder.trace_id if self._builder is not None else None,
|
|
128
|
+
run_id=self._run_id,
|
|
129
|
+
session_id=session_id,
|
|
130
|
+
)
|
|
131
|
+
self._builder = SpanTreeBuilder(
|
|
132
|
+
session_id=session_id,
|
|
133
|
+
run_id=self._run_id,
|
|
134
|
+
trace_id=self._status.trace_id,
|
|
135
|
+
clock_ms=self._clock.now_ms(),
|
|
136
|
+
)
|
|
137
|
+
self._status = ObservabilityStatus(
|
|
138
|
+
trace_id=self._builder.trace_id,
|
|
139
|
+
run_id=self._run_id,
|
|
140
|
+
session_id=session_id,
|
|
141
|
+
)
|
|
142
|
+
self._log("run_start", "开始一次运行")
|
|
143
|
+
return self._run_id
|
|
144
|
+
|
|
145
|
+
def finish_run(
|
|
146
|
+
self, *, totals: SessionTotals | None = None, session: SessionManager | None = None
|
|
147
|
+
) -> None:
|
|
148
|
+
"""一次 run 收尾:封口 span 树、导出、写 usage 到会话文件、打总结日志。"""
|
|
149
|
+
del totals # 会话累计总量给 UI 用;这里的汇总只覆盖本次 run。
|
|
150
|
+
target = session if session is not None else self._session
|
|
151
|
+
if self._builder is not None:
|
|
152
|
+
tree = self._builder.finish()
|
|
153
|
+
self._last_tree = tree
|
|
154
|
+
if self._settings.enabled:
|
|
155
|
+
self._exporter.export(tree)
|
|
156
|
+
self._status = ObservabilityStatus(
|
|
157
|
+
trace_id=tree.trace_id,
|
|
158
|
+
run_id=self._run_id,
|
|
159
|
+
session_id=self._session_id,
|
|
160
|
+
span_count=len(tree.spans),
|
|
161
|
+
recent_error_count=len(self._audit.recent_errors()),
|
|
162
|
+
)
|
|
163
|
+
summary = self.usage_summary()
|
|
164
|
+
self._log(
|
|
165
|
+
"run_summary",
|
|
166
|
+
"运行结束,汇总用量与费用",
|
|
167
|
+
usage=summary,
|
|
168
|
+
span_count=self._status.span_count,
|
|
169
|
+
)
|
|
170
|
+
if target is not None and self._settings.enabled and target.is_persisted():
|
|
171
|
+
self._persist_run_summary(target, summary)
|
|
172
|
+
|
|
173
|
+
def _persist_run_summary(self, session: SessionManager, summary: dict[str, JsonValue]) -> None:
|
|
174
|
+
"""把一次运行的汇总写进会话目录的旁路文件,不动会话树。
|
|
175
|
+
|
|
176
|
+
会话树的最后一条必须是助手消息(恢复时要知道"聊到哪一句"),把审计条目
|
|
177
|
+
追加到树尾会破坏这条不变量。旁路文件与会话同目录、同 session_id 前缀,
|
|
178
|
+
随会话一起归档、一起清理,又不进模型上下文。
|
|
179
|
+
"""
|
|
180
|
+
import json
|
|
181
|
+
from pathlib import Path
|
|
182
|
+
|
|
183
|
+
directory = Path(session.get_session_dir()) / "observability"
|
|
184
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
185
|
+
path = directory / f"{session.get_session_id()}.audit"
|
|
186
|
+
record: dict[str, JsonValue] = {
|
|
187
|
+
"type": "run_summary",
|
|
188
|
+
"sessionId": self._session_id,
|
|
189
|
+
"runId": self._run_id,
|
|
190
|
+
"traceId": self._status.trace_id,
|
|
191
|
+
"model": self._model,
|
|
192
|
+
"usage": summary,
|
|
193
|
+
"spanCount": self._status.span_count,
|
|
194
|
+
"permissionDecisions": [decision.to_wire() for decision in self._run_audits],
|
|
195
|
+
}
|
|
196
|
+
with path.open("a", encoding="utf-8", newline="\n") as handle:
|
|
197
|
+
handle.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n")
|
|
198
|
+
|
|
199
|
+
# ------------------------------------------------------------------ 事件与审计
|
|
200
|
+
|
|
201
|
+
def on_event(self, event: object) -> None:
|
|
202
|
+
"""订阅在会话上:所有 ``SessionEvent`` 都先经过这里。"""
|
|
203
|
+
if not self._settings.enabled:
|
|
204
|
+
return
|
|
205
|
+
kind: str = getattr(event, "type", "")
|
|
206
|
+
if self._builder is not None:
|
|
207
|
+
self._builder.on_event(event)
|
|
208
|
+
if kind == "tool_execution_start":
|
|
209
|
+
self._log(
|
|
210
|
+
"tool_call_start",
|
|
211
|
+
"工具开始执行",
|
|
212
|
+
tool_call_id=str(getattr(event, "tool_call_id", "")),
|
|
213
|
+
message=f"调用 {getattr(event, 'tool_name', '')}",
|
|
214
|
+
)
|
|
215
|
+
elif kind == "tool_execution_end":
|
|
216
|
+
duration = getattr(event, "duration_ms", None)
|
|
217
|
+
tool_name = getattr(event, "tool_name", "")
|
|
218
|
+
outcome = "失败" if getattr(event, "is_error", False) else "成功"
|
|
219
|
+
self._log(
|
|
220
|
+
"tool_call_end",
|
|
221
|
+
"工具执行结束",
|
|
222
|
+
tool_call_id=str(getattr(event, "tool_call_id", "")),
|
|
223
|
+
duration_ms=int(duration) if duration is not None else None,
|
|
224
|
+
message=f"{tool_name} {outcome}",
|
|
225
|
+
)
|
|
226
|
+
elif kind == "message_end":
|
|
227
|
+
message = getattr(event, "message", None)
|
|
228
|
+
if getattr(message, "role", None) == "assistant":
|
|
229
|
+
usage: Usage | None = getattr(message, "usage", None)
|
|
230
|
+
if usage is not None:
|
|
231
|
+
self._accumulate(usage)
|
|
232
|
+
self._log(
|
|
233
|
+
"model_usage",
|
|
234
|
+
"一次模型请求的用量",
|
|
235
|
+
model=f"{getattr(message, 'provider', '')}/{getattr(message, 'model', '')}",
|
|
236
|
+
duration_ms=getattr(message, "duration_ms", None),
|
|
237
|
+
usage=usage_to_wire(usage),
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
def record_permission(
|
|
241
|
+
self,
|
|
242
|
+
decision: PermissionDecision,
|
|
243
|
+
request: PermissionRequest,
|
|
244
|
+
*,
|
|
245
|
+
scope: ApprovalScope | None = None,
|
|
246
|
+
approver: str | None = None,
|
|
247
|
+
) -> None:
|
|
248
|
+
"""权限引擎判定后调用。只记判定与路径,不记完整参数。"""
|
|
249
|
+
if not self._settings.enabled:
|
|
250
|
+
return
|
|
251
|
+
# 审计记录本身也过过滤器:拒绝原因里可能带模型给的路径或命令片段。
|
|
252
|
+
record = permission_audit(
|
|
253
|
+
decision,
|
|
254
|
+
request,
|
|
255
|
+
session_id=self._session_id,
|
|
256
|
+
run_id=self._run_id,
|
|
257
|
+
scope=scope,
|
|
258
|
+
approver=approver,
|
|
259
|
+
timestamp_ms=self._clock.now_ms(),
|
|
260
|
+
redactor=self._redactor,
|
|
261
|
+
)
|
|
262
|
+
redacted_reason = record.reason
|
|
263
|
+
self._audit.append(record)
|
|
264
|
+
self._run_audits.append(record)
|
|
265
|
+
self._log(
|
|
266
|
+
"permission_decision",
|
|
267
|
+
"权限判定",
|
|
268
|
+
tool_call_id=decision.tool_call_id,
|
|
269
|
+
message=redacted_reason,
|
|
270
|
+
rule=decision.rule,
|
|
271
|
+
action=decision.action,
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
def shutdown(self) -> None:
|
|
275
|
+
self._exporter.shutdown()
|
|
276
|
+
|
|
277
|
+
# ------------------------------------------------------------------ 内部
|
|
278
|
+
|
|
279
|
+
def _accumulate(self, usage: Usage) -> None:
|
|
280
|
+
self._usage.input += usage.input
|
|
281
|
+
self._usage.output += usage.output
|
|
282
|
+
self._usage.cache_read += usage.cache_read
|
|
283
|
+
self._usage.cache_write += usage.cache_write
|
|
284
|
+
self._usage.total_tokens += usage.total_tokens or (
|
|
285
|
+
usage.input + usage.output + usage.cache_read + usage.cache_write
|
|
286
|
+
)
|
|
287
|
+
self._usage.cost.input += usage.cost.input
|
|
288
|
+
self._usage.cost.output += usage.cost.output
|
|
289
|
+
self._usage.cost.cache_read += usage.cost.cache_read
|
|
290
|
+
self._usage.cost.cache_write += usage.cost.cache_write
|
|
291
|
+
self._usage.cost.total += usage.cost.total
|
|
292
|
+
|
|
293
|
+
def _log(
|
|
294
|
+
self,
|
|
295
|
+
event: str,
|
|
296
|
+
default_message: str,
|
|
297
|
+
*,
|
|
298
|
+
level: str = "INFO",
|
|
299
|
+
**fields: JsonValue | None,
|
|
300
|
+
) -> None:
|
|
301
|
+
message_value = fields.pop("message", default_message)
|
|
302
|
+
all_fields: dict[str, JsonValue | None] = {
|
|
303
|
+
"session_id": self._session_id,
|
|
304
|
+
"run_id": self._run_id,
|
|
305
|
+
"model": self._model,
|
|
306
|
+
}
|
|
307
|
+
all_fields.update(fields)
|
|
308
|
+
self._logger.emit(
|
|
309
|
+
event,
|
|
310
|
+
_Source(timestamp_ms=self._clock.now_ms()),
|
|
311
|
+
message=str(message_value) if message_value is not None else default_message,
|
|
312
|
+
level=level,
|
|
313
|
+
**all_fields,
|
|
314
|
+
)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""导出器接口:OpenTelemetry 风格,默认关闭。
|
|
2
|
+
|
|
3
|
+
:class:`SpanExporter` 的方法名与参数形状对齐 OTel SDK 的 ``SpanExporter``,
|
|
4
|
+
调用方可以在应用启动时注入自己的 OTel exporter;Braid 自身只提供 noop、
|
|
5
|
+
内存与 JSONL 三种,不引入额外依赖。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Protocol, runtime_checkable
|
|
13
|
+
|
|
14
|
+
from braid_coding_agent.observability.spans import SpanTree
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@runtime_checkable
|
|
18
|
+
class SpanExporter(Protocol):
|
|
19
|
+
"""把一次运行的 span 树送出去。实现方自行决定批量、重试与目的地。"""
|
|
20
|
+
|
|
21
|
+
def export(self, tree: SpanTree) -> None: ...
|
|
22
|
+
def shutdown(self) -> None: ...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class NoopSpanExporter:
|
|
26
|
+
"""默认导出器:什么都不做。观测默认不外发。"""
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def exported(self) -> tuple[SpanTree, ...]:
|
|
30
|
+
return ()
|
|
31
|
+
|
|
32
|
+
def export(self, tree: SpanTree) -> None:
|
|
33
|
+
del tree
|
|
34
|
+
|
|
35
|
+
def shutdown(self) -> None:
|
|
36
|
+
return None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class InMemorySpanExporter:
|
|
40
|
+
"""收集导出内容,供测试与 ``/status`` 读取。"""
|
|
41
|
+
|
|
42
|
+
def __init__(self) -> None:
|
|
43
|
+
self._exported: list[SpanTree] = []
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def exported(self) -> tuple[SpanTree, ...]:
|
|
47
|
+
return tuple(self._exported)
|
|
48
|
+
|
|
49
|
+
def export(self, tree: SpanTree) -> None:
|
|
50
|
+
self._exported.append(tree)
|
|
51
|
+
|
|
52
|
+
def shutdown(self) -> None:
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class JsonFileSpanExporter:
|
|
57
|
+
"""把每棵树写成一行 JSON。给离线分析与 CI 归档用。"""
|
|
58
|
+
|
|
59
|
+
def __init__(self, path: Path) -> None:
|
|
60
|
+
self._path = path
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def exported(self) -> tuple[SpanTree, ...]:
|
|
64
|
+
return ()
|
|
65
|
+
|
|
66
|
+
def export(self, tree: SpanTree) -> None:
|
|
67
|
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
with self._path.open("a", encoding="utf-8", newline="\n") as handle:
|
|
69
|
+
handle.write(
|
|
70
|
+
json.dumps(tree.to_wire(), ensure_ascii=False, separators=(",", ":")) + "\n"
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def shutdown(self) -> None:
|
|
74
|
+
return None
|