代理跟踪
strace 对于AI代理。捕获并回放来自Claude Code、Cursor、Gemini CLI或任何MCP客户端的每个工具调用、提示和响应,然后分析、比较、审计和分享发生的事情。
为什么
编码代理在后台会话中重写20个文件。你会收到一个pull请求。你没有得到故事。它首先读取了哪些文件?为什么它调用同一个工具三次?在找到解决方案之前,什么失败了?
大多数工具跟踪LLM调用。这是一层。差距是围绕它的一切:工具调用、文件操作、决策点、错误恢复、代理运行的实际命令。 agent-strace 捕获整个会话,并允许您稍后重播。当您需要生产可观察性时,导出到Datadog、Honeycomb、New Relic或Splunk。
设置规则以自动停止代理——成本上限、接触错误的文件、过多的工具调用。代理人停了下来。没有提示,没有重试,没有损坏。
安装```bash
With uv (recommended)
uv tool install agent-strace
Or with pip
pip install agent-strace
Or run without installing
uvx agent-strace replay
**零依赖。** 仅限Python 3.10+标准库。
## VS代码/光标扩展名
安装 **特工斯特拉斯** 扩展,无需离开编辑器即可查看实时会话活动。
**安装:**
- 搜索 `agent-strace` 在“扩展”面板中(VS代码、游标或任何与Open VSX兼容的编辑器)
- 或从以下位置安装 open-vsx.org/extension/Siddhant-K代码/代理空间
**您将获得:**
|特性|描述|
|---|---|
|状态栏|实时成本、工具调用计数和活动工具名称。单击打开事件流。 |
|沟槽注释|代理读取的文件为蓝色边框,修改的文件为琥珀色。内联标签显示读/写计数。 |
|事件流面板|资源管理器侧栏中的实时提要——每个工具调用、文件操作、LLM请求和错误。 |
|暂停按钮|通过SIGSTOP在会话中停止代理。需要 `agent-strace watch` 在终端中运行。 |
**设置:**```bash
# 1. Install agent-strace
pip install agent-strace
# 2. Add hooks to Claude Code (one-time)
agent-strace setup
# 3. Open your project in VS Code / Cursor
# The extension activates automatically when .agent-traces/ exists
# 4. Start Claude Code — the status bar item appears immediately
当发生以下情况时,扩展会自动激活 .agent-traces/ 目录存在于工作区根目录中。无需配置。
暂停/恢复 (可选——需要手表运行):```bash
In a separate terminal, start the watcher
agent-strace watch
Then use the Pause button in the event stream panel,
or run: agent-trace: Pause Agent from the command palette
## 快速开始
### 选项1:Claude代码挂钩(完整会话捕获)
捕获一切:用户提示、助手响应和每个工具调用(Bash、编辑、写入、读取、代理、Grep、Glob、WebFetch、WebSearch、所有MCP工具)。```bash
agent-strace setup # prints hooks config JSON
agent-strace setup --global # for all projects
将输出添加到 .claude/settings.json。或手动粘贴:```json
{
"hooks": {
"UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "agent-strace hook user-prompt" }] }],
"PreToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "agent-strace hook pre-tool" }] }],
"PostToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "agent-strace hook post-tool" }] }],
"PostToolUseFailure": [{ "matcher": "", "hooks": [{ "type": "command", "command": "agent-strace hook post-tool-failure" }] }],
"Stop": [{ "hooks": [{ "type": "command", "command": "agent-strace hook stop" }] }],
"SessionStart": [{ "hooks": [{ "type": "command", "command": "agent-strace hook session-start" }] }],
"SessionEnd": [{ "hooks": [{ "type": "command", "command": "agent-strace hook session-end" }] }]
}
}
然后正常使用克劳德代码。```bash
agent-strace list # list sessions
agent-strace replay # replay the latest
agent-strace explain # plain-English summary of what the agent did
agent-strace stats # tool call frequency and timing
选项2:MCP代理(任何MCP客户端)
包装任何MCP服务器。适用于Cursor、Windsurf或任何MCP客户端。```bash
agent-strace record -- npx -y @modelcontextprotocol/server-filesystem /tmp
agent-strace replay
### 选项3:Python装饰器
直接包装您的工具功能。无需MCP。```python
from agent_trace import trace_tool, trace_llm_call, start_session, end_session, log_decision
start_session(name="my-agent") # add redact=True to strip secrets
@trace_tool
def search_codebase(query: str) -> str:
return search(query)
@trace_llm_call
def call_llm(messages: list, model: str = "claude-4") -> str:
return client.chat(messages=messages, model=model)
# Log decision points explicitly
log_decision(
choice="read_file_first",
reason="Need to understand current implementation before making changes",
alternatives=["read_file_first", "search_codebase", "write_fix_directly"],
)
search_codebase("authenticate")
call_llm([{"role": "user", "content": "Fix the bug"}])
meta = end_session()
print(f"Replay with: agent-strace replay {meta.session_id}")
CLI命令```
agent-strace setup [--redact] [--global] Generate Claude Code hooks config
agent-strace hook Handle a Claude Code hook event (internal)
agent-strace record -- Record an MCP stdio server session
agent-strace record-http [--port N] Record an MCP HTTP/SSE server session
agent-strace replay [session-id] Replay a session (default: latest)
agent-strace replay --format html [-o file] Export a self-contained HTML replay viewer
agent-strace replay --expand-subagents Inline subagent sessions under parent tool_call
agent-strace replay --tree Show session hierarchy without full replay
agent-strace list List all sessions
agent-strace explain [session-id] Explain a session in plain English
agent-strace stats [session-id] Show tool call frequency and timing
agent-strace stats --include-subagents Roll up stats across the full subagent tree
agent-strace inspect Dump full session as JSON
agent-strace export Export as JSON, CSV, NDJSON, or OTLP
agent-strace import Import a Claude Code JSONL session log
agent-strace cost [session-id] Estimate token cost for a session
agent-strace diff Compare two sessions structurally
agent-strace diff --compare Side-by-side table with verdict
agent-strace diff --semantic Compare sessions by outcome, not event order
agent-strace why [session-id] Trace the causal chain for an event
agent-strace audit [session-id] [--policy] Check tool calls against a policy file
agent-strace audit-tools [--repo .] [--approved] Detect Shadow MCP servers and undeclared agent activity in any repo
agent-strace policy [--output file] Generate .agent-scope.json from observed traces
agent-strace dashboard [--last N] [--html file] Aggregate stats and trends across sessions
agent-strace annotate Add notes, labels, or bookmarks to events
agent-strace token-budget Check token usage against model context limit
agent-strace watch [--rules file] Watch a live session; kill/pause on rule breach
agent-strace share [-o file] Export a self-contained HTML report
agent-strace standup [--session id] Standup report from session trace (no LLM)
agent-strace freshness [--scope glob] Context freshness check vs last session
agent-strace oncall --rotation-start DATE On-call readiness for agent-modified files
agent-strace curve [--export csv] Personal agent cost-efficiency curve
agent-strace inflation [--compare m1,m2] Token inflation calculator across model versions
agent-strace a2a-tree [session-id] Visualise A2A agent call graph
### 导入现有的Claude Code会话
已经运行了一个没有钩子的会话?直接从Claude Code的原生JSONL日志导入:```bash
# Discover available sessions
agent-strace import --discover
# Import a specific session
agent-strace import ~/.claude/projects//.jsonl
# Then use it like any captured session
agent-strace replay
agent-strace explain
agent-strace stats
Claude Code存储会话日志 ~/.claude/projects/导入捕获工具调用、令牌使用、子代理调用和会话元数据。
解释一个会话
获取代理所做工作的简单英文细分,按阶段组织,包括重试和浪费时间检测:```bash
agent-strace explain # latest session
agent-strace explain abc123 # specific session
Session: abc123 (2m 05s, 47 events)
Phase 1: fix the auth module (0:00–0:05, 5 events)
Read: AGENTS.md, src/auth.py
Phase 2: run tests — FAILED (0:05–1:20, 12 events)
Ran: python -m pytest
Ran: python -m pytest ← retry
Phase 3: run tests (1:20–2:05, 8 events)
Ran: uv run pytest
Files touched: 3 read, 0 written
Retries: 1 (wasted 1m 15s, 60% of session)
```
### 估计成本
按阶段细分估计的代币使用量和美元成本。旗帜在失败的阶段浪费了开支。```bash
agent-strace cost # latest session, sonnet pricing
agent-strace cost abc123 --model opus # specific session and model
agent-strace cost abc123 --input-price 3.0 --output-price 15.0 # custom pricing
Session: abc123 — Estimated cost: $0.0042
Model: sonnet | 8,200 input tokens, 3,100 output tokens
Phase 1: fix the auth module $0.0008 (19%) ...
Phase 2: run tests — FAILED $0.0021 (50%) ... ← wasted
Phase 3: run tests $0.0013 (31%) ...
Wasted on failed phases: $0.0021 (50%)
支持的型号: `sonnet` (默认), `opus`, `haiku`, `gpt4`, `gpt4o`。令牌计数根据有效载荷大小估算(`len / 4`);参见 ADR-0008 了解详情。
看 示例/会话分析.md 进行完整的演练,结合 `import`, `explain`,以及 `cost`.
### 秘密编辑
通过 `--redact` 以在API密钥、令牌和凭据进入磁盘之前从跟踪中剥离。```bash
# Stdio proxy with redaction
agent-strace record --redact -- npx -y @modelcontextprotocol/server-filesystem /tmp
# HTTP proxy with redaction
agent-strace record-http https://mcp.example.com --redact
检测到的模式:OpenAI(sk-*),GitHub(ghp_*, github_pat_*),AWS(AKIA*),人类学(sk-ant-*),松弛(xox*)、JWT、承载令牌、连接字符串(postgres://, mysql://),以及以下键下的任何值 password, secret, token, api_key, authorization.
HTTP/SSE代理
对于使用HTTP传输而不是stdio的MCP服务器:```bash
Proxy a remote MCP server
agent-strace record-http https://mcp.example.com --port 3100
Your agent connects to http://127.0.0.1:3100 instead of the remote server
All JSON-RPC messages are captured, tool call latency is measured
代理转发POST `/message` 和GET `/sse` 将JSON-RPC消息双向捕获到远程服务器。
### 回放输出
用钩子捕获的真实Claude Code会话:
Session Summary```
Session Summary
──────────────────────────────────────────────────
Session: 201da364-edd6-49
Command: claude-code (startup)
Agent: claude-code
Duration: 112.54s
Tool calls: 8
Errors: 3
──────────────────────────────────────────────────
+ 0.00s ▶ session_start
+ 0.07s 👤 user_prompt
"how many tests does this project have? run them and tell me the results"
+ 3.55s → tool_call Glob
**/*.test.*
+ 3.55s → tool_call Glob
**/test_*.*
+ 3.60s ← tool_result Glob (51ms)
+ 6.06s → tool_call Bash
$ python -m pytest tests/ -v 2>&1
+ 27.65s ✗ error Bash
Command failed with exit code 1
+ 29.89s → tool_call Bash
$ python3 -m pytest tests/ -v 2>&1
+ 40.56s ✗ error Bash
No module named pytest
+ 45.96s → tool_call Bash
$ which pytest || ls /Users/siddhant/Desktop/test-agent-trace/ 2>&1
+ 46.01s ← tool_result Bash (51ms)
+ 48.18s → tool_call Read
/Users/siddhant/Desktop/test-agent-trace/pyproject.toml
+ 48.23s ← tool_result Read (43ms)
+ 51.43s → tool_call Bash
$ uv run --with pytest pytest tests/ -v 2>&1
+1m43.67s ← tool_result Bash (5.88s)
75 tests, all passing in 3.60s
+1m52.54s 🤖 assistant_response
"75 tests, all passing in 3.60s. Breakdown by file: ..."
工具调用显示实际值:命令、文件路径、glob模式。错误显示了失败的原因。助理回复中没有降价。
过滤```bash
Show only tool calls and errors
agent-strace replay --filter tool_call,error
Replay with timing (watch it unfold)
agent-strace replay --live --speed 2
### 出口```bash
# JSON array
agent-strace export a84664 --format json
# CSV (for spreadsheets)
agent-strace export a84664 --format csv
# NDJSON (for streaming pipelines)
agent-strace export a84664 --format ndjson
跟踪格式
痕迹存储在以下目录中 .agent-traces/:```
.agent-traces/
a84664242afa4516/
meta.json # session metadata
events.ndjson # newline-delimited JSON events
每个事件都是一行JSON:```json
{
"event_type": "tool_call",
"timestamp": 1773562735.09,
"event_id": "bf1207728ee6",
"session_id": "a84664242afa4516",
"data": {
"tool_name": "read_file",
"arguments": {"path": "src/auth.py"}
}
}
事件类型
| 类型 | 描述 |
|---|---|
session_start |
跟踪会话已开始 |
session_end |
跟踪会话已结束 |
user_prompt |
用户向代理提交了提示 |
assistant_response |
代理生成了文本响应 |
tool_call |
代理调用了一个工具 |
tool_result |
工具返回了一个结果 |
llm_request |
代理向LLM发送了提示 |
llm_response |
LLM返回了一个完成项 |
file_read |
代理读取文件 |
file_write |
代理写了一个文件 |
decision |
代理人在备选方案之间进行选择 |
error |
有些事情失败了 |
事件相互关联。A. tool_result 有一个 parent_id 指向其 tool_call。这使您可以测量每个工具的延迟并跟踪整个调用链。
与克劳德代码、光标、风帆一起使用
Claude Code(钩子,推荐)
捕获整个会话:提示、响应和每个工具调用。看 示例/claude_code_config.md 查看完整配置。```bash
agent-strace setup # per-project config
agent-strace setup --redact --global # all projects, with secret redaction
### 光标
编辑 `~/.cursor/mcp.json` (全球)或 `.cursor/mcp.json` (每个项目):```json
{
"mcpServers": {
"filesystem": {
"command": "agent-strace",
"args": ["record", "--name", "filesystem", "--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
}
}
}
帆板运动
编辑 ~/.codeium/windsurf/mcp_config.json:```json
{
"mcpServers": {
"filesystem": {
"command": "agent-strace",
"args": ["record", "--name", "filesystem", "--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
}
}
}
### 任何MCP客户端
对于任何使用MCP over stdio的工具,模式都是一样的:
1. 更换服务器 `command` 随着 `agent-strace`
1. 前置 `record --name --` 到原始args
1. 正常使用工具
1. 跑 `agent-strace replay` 看看发生了什么
看 示例/ 完整配置文件的目录。
### 子代理追踪
当代理生成子代理(例如Claude Code的代理工具)时,会话会链接到父子树中。内联回放完整树或查看紧凑的层次结构:```bash
# Inline replay: subagent events appear under the parent tool_call that spawned them
agent-strace replay --expand-subagents
# Compact hierarchy: session IDs, durations, tool counts
agent-strace replay --tree
# Aggregated stats across the full tree (tokens, tool calls, errors)
agent-strace stats --include-subagents
``````
▶ session_start a84664242afa agent=claude-code depth=0
+ 0.00s 👤 "refactor the auth module"
+ 1.23s → tool_call Agent "extract helper functions"
│ ▶ session_start b12345678901 agent=claude-code depth=1
│ + 0.00s → tool_call Read src/auth.py
│ + 0.12s ← tool_result
│ + 0.45s → tool_call Write src/auth_helpers.py
│ + 0.51s ■ session_end
+ 3.10s ← tool_result
+ 3.20s ■ session_end
子代理会话通过以下方式链接 parent_session_id 和 parent_event_id 会话中元数据。没有这些字段的现有会话不受影响。
会话差异
从结构上比较两个会话。有助于理解为什么同一个提示在不同的运行中产生不同的结果,或者将中断的会话与已知的良好会话进行比较。使用LCS通过标签对齐相位,然后在触摸的文件中按相位差异运行命令,并报告结果:```bash
agent-strace diff abc123 def456
Comparing: abc123 vs def456
Diverged at phase 2:
Phase 2: run tests
abc123 only: $ python -m pytest
def456 only: $ uv run pytest
abc123: 4m 12s, 47 events, 8 tools, 2 retries
def456: 2m 05s, 31 events, 5 tools, 0 retries
```
### 因果链(为什么)
从任何事件向后追溯,找出导致它的原因。运行 `agent-strace replay ` 第一—— `#N` 左列中的数字是事件编号:```bash
agent-strace why abc123 4
Why did event #4 happen?
4 tool_call: Bash $ pytest tests/
Causal chain (root → target):
1 user_prompt: "run the test suite"
(prompt at #1 triggered this)
← # 3 error: exit 1
(retry after error at #3)
← # 4 tool_call: Bash $ pytest tests/
通过以下方式检测因果关系 `parent_id` (工具_结果→ tool_call),错误→重试匹配(相同的工具和命令)、路径引用(包含稍后调用使用的路径的tool_result文本),并读取→在同一文件中写入配对。
### 权限审核
对照策略文件检查会话中的每个工具调用。自动标记敏感文件访问(`.env`, `*.pem`, `.ssh/*`, `.github/workflows/*`等),即使没有政策:```bash
agent-strace audit # latest session, no policy required
agent-strace audit abc123 --policy .agent-scope.json
# In CI: fail the build if the agent accessed anything outside policy
agent-strace audit --policy .agent-scope.json || exit 1
``````
AUDIT: Session abc123 (47 events, 23 tool calls)
✅ Allowed (19):
Read src/auth.py
Ran: uv run pytest
⚠️ No policy (2):
Read README.md (no file read policy for this path)
❌ Violations (2):
Read .env ← denied by files.read.deny
Ran: curl https://example.com ← denied by commands.deny
🔐 Sensitive files accessed (1):
Read .env (event #12)
发现违规时以代码1退出——可在CI中使用。
策略文件 (.agent-scope.json):```json
{
"files": {
"read": { "allow": ["src/", "tests/"], "deny": [".env"] },
"write": { "allow": ["src/"], "deny": [".github/"] }
},
"commands": {
"allow": ["pytest", "uv run", "cat"],
"deny": ["curl", "wget", "rm -rf"]
},
"network": { "deny_all": true, "allow": ["localhost"] }
}
球形图案支持 `**` 作为递归通配符。文件读取策略适用于 `Read`, `View`, `Grep`,以及 `Glob` 工具调用。网络策略检查嵌入的URL `Bash` 命令。
### 根据您的跟踪自动生成策略
而不是写作 `.agent-scope.json` 手动让代理跟踪观察几个会话,并为您生成一个会话:```bash
# Dry-run: print the suggested policy without writing anything
agent-strace policy
# Write it to disk
agent-strace policy --output .agent-scope.json
# Observe a specific set of sessions
agent-strace policy --last 20 --output .agent-scope.json
生成的策略涵盖了代理实际使用的每个文件路径和命令,并折叠成glob模式。检查它,收紧拒绝列表,然后将其与代码一起提交。
PII屏蔽
敏感数据在进入磁盘之前会被屏蔽。在跟踪处理用户数据、凭据或日志文件中不希望出现的任何内容的代理时非常有用。```bash
Stdio proxy with masking
agent-strace record --mask -- npx -y @modelcontextprotocol/server-filesystem /tmp
HTTP proxy with masking
agent-strace record-http https://mcp.example.com --mask
默认情况下屏蔽:电子邮件地址、电话号码、信用卡号码、美国社会保障号码和AWS ARN。您也可以致电 `mask_event_data()` 在共享或导出事件之前,直接从现有会话中清除事件。
### 多会话仪表板
获取所有会话的汇总视图,这对于发现趋势、异常值和成本峰值非常有用,而无需单独打开每个会话。```bash
agent-strace dashboard # all sessions
agent-strace dashboard --last 20 # last 20 sessions
agent-strace dashboard --since 2024-06-01 # since a date
agent-strace dashboard --html report.html # self-contained HTML export
终端视图显示了总工具调用、错误、令牌和估计成本,以及每个指标随时间变化的ASCII火花线图和顶级工具频率表。HTML导出是自包含的,不需要服务器。
会话归因
每个会话都记录了谁和什么产生了它。当你打开跟踪时,你会看到操作系统用户、检测到的代理提供者、git仓库和分支以及父进程链。```bash
agent-strace show SESSION_ID
Attribution
User: alice
Provider: claude-code
Branch: feat/my-feature
Commit: a1b2c3d
CWD: /home/alice/projects/myapp
检测到的提供商: `claude-code`, `cursor`, `github-copilot`, `cody`, `continue`,以及通用 `mcp-client` 退路。归因是自动收集的,无需配置。
### 回放注释
为录制会话中的任何事件添加注释、标签和书签。可用于代码审查、调试和构建eval数据集。```bash
# Add a note to event #12
agent-strace annotate SESSION_ID 12 --note "Why did it call bash here instead of write_file?"
# Tag an event
agent-strace annotate SESSION_ID 12 --label regression
# Bookmark for quick navigation in the HTML viewer
agent-strace annotate SESSION_ID 12 --bookmark
# List all annotations
agent-strace annotate SESSION_ID --list
# Remove one
agent-strace annotate SESSION_ID 12 --delete ANNOTATION_ID
注释与会话同时存在,并在共享HTML报告中显示为书签侧边栏。它们也可用于构建eval数据集——将会话标记为 pass / fail / interesting 稍后过滤这些标签。
代币预算跟踪
长时间运行的代理可以悄无声息地烧穿模型的上下文窗口。令牌预算命令显示您的接近程度,并在达到限制之前发出警告。```bash
agent-strace token-budget SESSION_ID
agent-strace token-budget SESSION_ID --model claude-3-5-sonnet
agent-strace token-budget SESSION_ID --model gpt-4o --warn-at 75
在监视模式下,实时应用相同的阈值:```bash
agent-strace watch --max-context-pct 80 SESSION_ID
支持的型号及其限制:
| 模型 | 上下文 |
|---|---|
| claude3-5-sonnet | 20万代币 |
| claude-3-opus | 20万代币 |
| gpt-4o | 128k代币 |
| gpt-4-turbo | 128k代币 |
| gemini-1.5-pro | 1M代币 |
通过 --limit 为任何其他模型设置自定义天花板。
语义会话差异
通过以下方式比较两个会话 结果 而不是原始事件顺序。可用于跨模型版本或提示更改的回归测试代理行为。```bash
agent-strace diff SESSION_A SESSION_B --semantic
``````
Semantic diff: SESSION_A vs SESSION_B
Tools added: write_file
Tools removed: bash
Δ tool calls: +3
Δ errors: -2
Δ tokens: +1,200
Outcome: improved (fewer errors, same task completed)
导出CI断言的结构化JSON报告:```bash
agent-strace diff SESSION_A SESSION_B --semantic --eval-config eval.json
丰富的并排比较
--compare 生成一个包含成本、持续时间、工具调用、冗余读取、上下文重置、文件修改和错误的结构化表,其确定性判断不需要LLM。```bash
agent-strace diff SESSION_A SESSION_B --compare
新指标: **冗余读取** (文件读取多次), **上下文重置** (LLM请求间隔>120秒), **方法分歧** (行为不同的第一阶段对)。可用于在CI中断言。
### 失控会话的终止开关
将声明性规则文件添加到 `agent-strace watch` 当会话超过阈值时暂停、终止或发出警报。当规则触发时,代理会停止——没有提示、没有重试、没有损坏。```bash
agent-strace watch --rules .watch-rules.json
agent-strace watch --rules .watch-rules.json --dry-run # evaluate without acting
示例 .watch-rules.json:```json
[
{ "condition": "cost_usd", "threshold": 0.50, "action": "kill" },
{ "condition": "file_path", "glob": "**/production.env", "action": "kill" },
{ "condition": "files_modified", "threshold": 30, "action": "pause" }
]
**规则条件:** `files_modified`, `cost_usd`, `consecutive_test_failures`, `duration_minutes`, `file_path` (glob)。
**行动:**
- `pause` --SIGSTOP代理进程(使用SIGCONT恢复)
- `kill` --SIGTERM,然后5秒后SIGKILL;自动生成尸检
- `alert` --仅日志,无中断
### 阴影MCP检测
检测任何回购中的影子MCP服务器和未声明的代理活动-无网络调用,无API密钥。A. CSA对418名安全专业人员的调查 发现82%的企业在过去一年中发现了至少一个他们的安全团队不知道的人工智能代理。 `audit-tools` 找到你的。```bash
agent-strace audit-tools
agent-strace audit-tools --repo . --since "90 days ago" --approved cursor,copilot
检测到的工具:Claude Code、Cursor、GitHub Copilot、Codex/ChatGPT、Windsurf、Aider、Gemini CLI——通过文件信号识别(.cursorrules, CLAUDE.md, .github/copilot-instructions.md等等)和提交消息模式。标记中未经批准的工具、未知的LLM API终结点 .env 例如最近提交的文件中的历史和PII模式。
HTML会话回放查看器
为任何会话生成单个文件HTML查看器。没有服务器,没有依赖关系——在任何浏览器中打开。```bash
agent-strace replay --format html
agent-strace replay --format html --output review.html SESSION_ID
查看器包括一个动画事件时间线、洗涤栏、运行成本计数器、点击展开事件详细信息、颜色编码的事件类型和深色主题。所有事件数据都以JSON常量的形式嵌入,这对于附加到PR评论中非常有用。
### 站立报告
从会话跟踪生成结构化站立——不需要LLM调用。```bash
agent-strace standup
agent-strace standup --session SESSION_ID
报告涵盖:读取和修改的文件、尝试的方法(包括从重试模式中检测到的放弃方法)、添加的新依赖关系、编写的TODO/FIXME注释、要审查的大更改和身份验证/迁移模式,以及会话统计数据(工具调用、重试、错误)。
上下文新鲜度检查
在将任务交给代理之前,请检查其代码库的最后一个视图有多陈旧。```bash
agent-strace freshness
agent-strace freshness --since 2026-04-01 --scope "src/**"
报告自上次会话以来更改的文件、每种文件更改类型和行数、0-100的新鲜度评分以及估计的追赶读取时间。从中自动检测作用域 `CLAUDE.md` / `AGENTS.md`,或被覆盖 `--scope`.
### 随时待命
交叉引用代理根据git历史修改文件,以在轮换前发现认知差距。```bash
agent-strace oncall --rotation-start 2026-04-25
agent-strace oncall --rotation-start 2026-04-25 --scope "src/payments/**"
对于代理在过去N天内写入的每个文件:修改时间、更改行数、估计读取时间以及旋转前的总追赶时间。
成本效益曲线
分析存储的会话历史记录,看看哪些任务类型值得委托给代理。```bash
agent-strace curve
agent-strace curve --min-sessions 10 --export csv
会话分为10种任务类型(单元测试、调试、重构、架构等),并与社区最佳点基准进行比较。每种类型的判断: **高效/过于理想/自己动手**。对于运行超过1.5倍最佳点的类型,计算潜在的月度节省。
### 代币通货膨胀计算器
在承诺升级之前,测量切换模型版本对令牌化器成本的影响-不需要API调用。```bash
agent-strace inflation
agent-strace inflation --compare claude-opus-4-6,claude-opus-4-7 --sessions 30
将每个模型的膨胀系数应用于存储的会话内容,并按内容类型(系统提示、工具定义、用户消息、助理消息)细分影响。每个会话、每日和每月的项目成本增量。
| 型号 | 系数 |
|---|---|
| claude-opus-4-7 | 1.38×(群落中位数:1.3-1.47×,2026年4月) |
| gpt-4o | 1.05×(cl100kbase)→ 200kbase) |
A2A协议支持
根据Google A2A规范,对代理间呼叫提供一流的支持。A2A呼叫被捕获为 TOOL_CALL 事件与 event_subtype=a2a_call --与所有现有的回放和导出工具向后兼容。```bash
agent-strace a2a-tree
agent-strace a2a-tree SESSION_ID --format json
通过以下步骤构建完整的代理调用图 `sub_session_id` 链接和 `parent_session_id` 反向引用。呈现为ASCII树或导出为Jaeger、Tempo或任何OpenTetry后端的OTLP兼容跨度。
## 与安全关键代码库一起使用
当AI编码代理在处理秘密、证明逻辑或加密材料的代码库上工作时,代理strace提供了两件事:对每个被触摸的文件和每个命令运行的审计跟踪,以及在秘密到达任何日志之前对其进行自动编校。
### 敏感存储库的推荐设置
添加 `.claude/settings.json` 到repo根目录并提交。每个在repo上工作的开发人员都会自动获得相同的工具:```json
{
"hooks": {
"PreToolUse": [{
"matcher": ".*",
"hooks": [{ "type": "command", "command": "agent-strace hook pre-tool" }]
}],
"PostToolUse": [{
"matcher": ".*",
"hooks": [{ "type": "command", "command": "agent-strace hook post-tool" }]
}]
}
}
或者使用setup命令:```bash
cd your-sensitive-repo
agent-strace setup --redact
### TEE和机密计算栈的秘密编辑
对于处理TEE机密的代码库,以下模式会自动编辑:
|秘密类型|图案匹配|
|-------------|----------------|
|EKM共享机密|64个字符十六进制字符串(例如。 `EKM_SHARED_SECRET`) |
|持有者代币| `Bearer [A-Za-z0-9+/=]{20,}` |
|无烟煤API键| `sk-ant-...` |
|AWS凭据| `AKIA...`, `aws_secret_access_key` |
|私钥|PEM块|
如果您的代码库使用自定义密钥格式,请通过以下方式添加模式 `--redact-pattern`:```bash
agent-strace setup --redact --redact-pattern "ATTESTATION_KEY=[A-Fa-f0-9]{64}"
示例:使试剂远离敏感成分
结合 代理权限 强制代理根本无法访问安全关键组件,并使用代理strace审核他们访问的所有内容:```
Agent scope: frontend/ only (enforced by OpenFGA — no tuple = no access)
agent-strace scope: all tool calls logged, secrets redacted, exported to Grafana
代理人试图阅读 `cvm/attestation-service/` 或 `cvm/auth-service/` 在到达文件系统之前,在授权层被阻止。特工strace记录了被拒绝的尝试及其原因。
______________________________________________________________________
## 生产跟踪(OTLP出口)
将会话导出为OpenTetry跨越到现有的可观察性堆栈。会话变成了痕迹。工具调用变为具有持续时间和输入的跨度。错误会导致异常事件。零新依赖关系。
### 数据狗```bash
# Via the Datadog Agent's OTLP receiver (port 4318)
agent-strace export --format otlp \
--endpoint http://localhost:4318
# Or via Datadog's OTLP intake directly
agent-strace export --format otlp \
--endpoint https://http-intake.logs.datadoghq.com:443 \
--header "DD-API-KEY: $DD_API_KEY"
蜂窝```bash
agent-strace export --format otlp \
--endpoint https://api.honeycomb.io \
--header "x-honeycomb-team: $HONEYCOMB_API_KEY" \
--service-name my-agent
### 新遗迹```bash
agent-strace export --format otlp \
--endpoint https://otlp.nr-data.net \
--header "api-key: $NEW_RELIC_LICENSE_KEY"
斯普兰克```bash
agent-strace export --format otlp \
--endpoint https://ingest..signalfx.com \
--header "X-SF-Token: $SPLUNK_ACCESS_TOKEN"
### Grafana Tempo/Jaeger```bash
# Local collector
agent-strace export --format otlp \
--endpoint http://localhost:4318
转储OTLP JSON而不发送```bash
Inspect the OTLP payload
agent-strace export --format otlp > trace.json
### 它是如何映射的
|代理跟踪|OpenTetry|
|---|---|
|会话|跟踪|
|tool_call+tool_result|span(带持续时间)|
|错误|span,错误状态+异常事件|
|根span上的user_prompt|事件|
|根span上的assistant_response|事件|
|session_id |跟踪id|
|event_id | span id|
|parent_id |父span id|
## 运作原理
### 克劳德代码挂钩```
Claude Code agentic loop
├── UserPromptSubmit → agent-strace hook user-prompt
├── PreToolUse → agent-strace hook pre-tool
├── PostToolUse → agent-strace hook post-tool
├── PostToolUseFailure → agent-strace hook post-tool-failure
├── Stop → agent-strace hook stop
├── SessionStart → agent-strace hook session-start
└── SessionEnd → agent-strace hook session-end
↓
.agent-traces/
Claude Code在其代理循环的每个阶段都会触发挂钩事件。代理strace注册为处理程序,从stdin读取JSON,并写入跟踪事件。每个钩子都是一个单独的过程。会话状态存在 .agent-traces/.active-session 因此,PreToolUse和PostToolUse可以相互关联以进行延迟测量。
MCP stdio代理```
Agent ←→ agent-strace proxy ←→ MCP Server (stdio)
↓
.agent-traces/
代理读取JSON-RPC消息(Content-Length框架或换行符分隔),对每条消息进行分类,并写入跟踪事件。邮件将原封不动地转发。代理和服务器不知道代理存在。
### MCP HTTP/SSE代理```
Agent ←→ agent-strace proxy (localhost:3100) ←→ Remote MCP Server (HTTPS)
↓
.agent-traces/
同样的想法,不同的运输方式。监听本地端口,将POST和SSE请求转发到远程服务器,双向捕获每条JSON-RPC消息。
装饰模式```python
@trace_tool
def my_function(x):
return x * 2
装饰师记录了一个 `tool_call` 执行前的事件和 `tool_result` 之后。错误和计时会自动捕获。
### 秘密编辑
当 `--redact` 已启用(或 `redact=True` 在decorator API中),跟踪事件在到达磁盘之前通过编校过滤器。过滤器检查密钥名称(`password`, `api_key`)以及价值模式(`sk-*`, `ghp_*`JWTs)。修改后的值变为 `[REDACTED]`原始数据永远不会被存储。
## 项目结构```
src/agent_trace/
__init__.py # version
models.py # TraceEvent, SessionMeta, EventType
store.py # NDJSON file storage
hooks.py # Claude Code hooks integration
proxy.py # MCP stdio proxy
http_proxy.py # MCP HTTP/SSE proxy
redact.py # secret redaction (key/value pattern matching)
masking.py # PII masking (email, phone, CC, SSN, ARN)
otlp.py # OTLP/HTTP JSON exporter with GenAI semantic conventions
replay.py # terminal replay, HTML viewer export
decorator.py # @trace_tool, @trace_llm_call, log_decision
jsonl_import.py # Claude Code JSONL session import
explain.py # session phase detection and plain-English summary
cost.py # token and cost estimation
subagent.py # parent-child session tree, tree replay, stats rollup
diff.py # structural, semantic, and side-by-side session comparison
why.py # causal chain tracing (backwards event walk)
audit.py # policy-based tool call checking, sensitive file detection
audit_tools.py # shadow AI detection (file signals + commit patterns)
policy.py # generate .agent-scope.json from observed traces
attribution.py # session attribution (user, process ancestry, git context)
dashboard.py # multi-session aggregate view and trend charts
annotate.py # replay annotations (notes, labels, bookmarks)
token_budget.py # token budget tracking and context window early warning
watch.py # live session watcher with rule-based kill switch
share.py # self-contained HTML report export
standup.py # standup report from session trace (no LLM)
freshness.py # context freshness check vs last session
oncall.py # on-call readiness for agent-modified files
curve.py # personal agent cost-efficiency curve
inflation.py # token inflation calculator across model versions
a2a.py # A2A protocol support and cross-agent trace correlation
cli.py # CLI entry point
ADRs/ # Architecture Decision Records
运行测试```bash
pytest
## 发展```bash
git clone https://github.com/Siddhant-K-code/agent-trace.git
cd agent-trace
# Run tests
pytest
# Run the example
PYTHONPATH=src python examples/basic_agent.py
# Replay the example
PYTHONPATH=src python -m agent_trace.cli replay
# Build the package
uv build
# Install locally for testing
uv tool install -e .
相关
- 架构决策记录 -设计决策及其基本原理
- 代理可观测性差距(博客) -此工具解决的问题
- 代理可观察性间隙(线程) -关于X的讨论
- 代理工程指南 -第7、9、10章涉及代理人担保;第14、15、16章涵盖了可观测性
- 开放遥测GenAI -LLM跟踪的语义约定(补充)
赞助商
如果代理跟踪为您节省了调试代理会话的时间,请考虑 赞助该项目。它帮助我不断构建这样的工具,并免费发布。
许可证
MIT。随心所欲地使用它。
