-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcli.py
More file actions
1820 lines (1598 loc) · 86 KB
/
Copy pathcli.py
File metadata and controls
1820 lines (1598 loc) · 86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""CLI entry point.
Usage:
agent-strace record [--no-redact] -- <server-command> [args...]
agent-strace record-http [--no-redact] --url <remote-url> [--port <local-port>]
agent-strace setup [--no-redact] [--global]
agent-strace hook <event>
agent-strace replay [session-id]
agent-strace list
agent-strace inspect <session-id>
agent-strace export <session-id> [--format json|csv|otlp]
"""
from __future__ import annotations
import argparse
import csv
import json
import os
import sys
import time
from pathlib import Path
from . import __version__
from .hooks import hook_main
from .http_proxy import HTTPProxyServer
from .a2a import cmd_a2a_tree
from .mcp_server import cmd_mcp
from .annotate import cmd_annotate
from .approval import cmd_approval
from .rbac import cmd_rbac
from .iac import cmd_apply, cmd_config_diff
from .sso import cmd_auth
from .baseline import cmd_baseline
from .compliance import cmd_audit_readiness, cmd_compliance, cmd_export_eu_ai_act, cmd_verify_export
from .drift import cmd_drift, cmd_fingerprint
from .identity import cmd_identity
from .workspace import cmd_workspace
from .langfuse_export import cmd_export_scores
from .oncall import cmd_oncall
from .optimize import cmd_optimize
from .freshness import cmd_freshness
from .standup import cmd_standup
from .audit import cmd_audit, verify_chain
from .cost import cmd_cost
from .cognitive_debt import cmd_cognitive_debt
from .context_score import cmd_context_score
from .curve import cmd_curve
from .dashboard import cmd_dashboard
from .shadow_ai import cmd_audit_tools
from .inflation import cmd_inflation
from .diff import cmd_diff
from .eval import cmd_eval
from .explain import cmd_explain
from .jsonl_import import cmd_import
from .policy import cmd_policy
from .postmortem import cmd_postmortem
from .project_budget import enforce_new_session_budget, load_project_budget_config
from .share import cmd_share
from .token_budget import cmd_token_budget
from .anonymize import cmd_anonymize_export
from .integrations import detect_and_instrument, _INTEGRATIONS
from .budget_report import cmd_budget_report
from .team_report import cmd_team_report
from .compare import cmd_compare
from .freeze import cmd_freeze, cmd_regression
from .timeline import cmd_timeline
from .config_watch import cmd_config_watch
from .lint import cmd_lint
from .mcp_scan import cmd_mcp_scan
from .retention import cmd_retention
from .sample import cmd_sample
from .server import cmd_server
from .watch import cmd_watch
from .why import cmd_why
from .models import EventType, SessionMeta, TraceEvent
from .proxy import MCPProxy
from .replay import format_event, format_summary, list_sessions, replay_session
from .store import TraceStore
from .subagent import cmd_replay_tree, cmd_stats_tree, cmd_tree
from .why import cmd_why
def _print_live_event(event: TraceEvent) -> None:
"""Print event to stderr during recording."""
line = format_event(event)
sys.stderr.write(f"\r{line}\n")
sys.stderr.flush()
def _redact_setting(args: argparse.Namespace) -> bool | None:
"""Return explicit redaction setting, or None to use env/defaults."""
if getattr(args, "no_redact", False):
return False
if getattr(args, "redact", False):
return True
return None
def _parent_session_id(args: argparse.Namespace) -> str:
return (
getattr(args, "parent", None)
or os.environ.get("AGENT_STRACE_PARENT_SESSION", "")
)
def _resolve_parent_session_id(store: TraceStore, args: argparse.Namespace) -> str:
raw = _parent_session_id(args)
if not raw:
return ""
return store.find_session(raw) or raw
def _parent_event_id() -> str:
return os.environ.get("AGENT_STRACE_PARENT_EVENT", "")
def _parent_depth(store: TraceStore, parent_session_id: str) -> int:
if not parent_session_id:
return 0
try:
parent_meta = store.load_meta(parent_session_id)
return parent_meta.depth + 1
except Exception:
return 1
def cmd_record(args: argparse.Namespace) -> int:
"""Record an MCP server session."""
store = TraceStore(args.trace_dir, redact=_redact_setting(args))
budget_config = load_project_budget_config()
if budget_config.enabled and not enforce_new_session_budget(
store, budget_config, sys.stderr
):
return 1
server_cmd = args.server_cmd
# Strip leading '--' separator added by argparse REMAINDER
if server_cmd and server_cmd[0] == "--":
server_cmd = server_cmd[1:]
parent_session_id = _resolve_parent_session_id(store, args)
meta = SessionMeta(
agent_name=args.name or "",
command=" ".join(server_cmd),
parent_session_id=parent_session_id,
parent_event_id=_parent_event_id(),
depth=_parent_depth(store, parent_session_id),
)
store.create_session(meta)
if not args.quiet:
sys.stderr.write(
f"agent-strace: recording session {meta.session_id}\n"
f"agent-strace: command: {' '.join(server_cmd)}\n"
)
on_event = _print_live_event if args.verbose else None
proxy = MCPProxy(
server_command=server_cmd,
store=store,
session_meta=meta,
on_event=on_event,
redact=args.redact,
)
returncode = proxy.run()
if not args.quiet:
sys.stderr.write(
f"\nagent-strace: session {meta.session_id} complete\n"
f"agent-strace: {meta.tool_calls} tool calls, "
f"{meta.llm_requests} llm requests, "
f"{meta.errors} errors\n"
f"agent-strace: replay with: agent-trace replay {meta.session_id}\n"
)
return returncode
def cmd_record_http(args: argparse.Namespace) -> int:
"""Record a remote MCP server session over HTTP/SSE."""
store = TraceStore(args.trace_dir, redact=_redact_setting(args))
budget_config = load_project_budget_config()
if budget_config.enabled and not enforce_new_session_budget(
store, budget_config, sys.stderr
):
return 1
parent_session_id = _resolve_parent_session_id(store, args)
meta = SessionMeta(
agent_name=args.name or "",
command=f"http-proxy -> {args.url}",
parent_session_id=parent_session_id,
parent_event_id=_parent_event_id(),
depth=_parent_depth(store, parent_session_id),
)
store.create_session(meta)
if not args.quiet:
sys.stderr.write(
f"agent-strace: recording HTTP session {meta.session_id}\n"
f"agent-strace: proxying http://127.0.0.1:{args.port} -> {args.url}\n"
)
on_event = _print_live_event if args.verbose else None
proxy = HTTPProxyServer(
remote_url=args.url,
local_port=args.port,
store=store,
session_meta=meta,
on_event=on_event,
redact=args.redact,
)
proxy.run()
if not args.quiet:
sys.stderr.write(
f"\nagent-strace: session {meta.session_id} complete\n"
f"agent-strace: {meta.tool_calls} tool calls, "
f"{meta.llm_requests} llm requests, "
f"{meta.errors} errors\n"
f"agent-strace: replay with: agent-strace replay {meta.session_id}\n"
)
return 0
def cmd_replay(args: argparse.Namespace) -> int:
"""Replay a recorded session."""
# Delegate to tree replay when subagent flags are set
if getattr(args, "expand_subagents", False) or getattr(args, "tree", False):
return cmd_replay_tree(args)
store = TraceStore(args.trace_dir)
session_id = args.session_id
if not session_id:
session_id = store.get_latest_session_id()
if not session_id:
sys.stderr.write("No sessions found.\n")
return 1
# support prefix matching
if not store.session_exists(session_id):
found = store.find_session(session_id)
if found:
session_id = found
else:
sys.stderr.write(f"Session not found: {session_id}\n")
return 1
event_filter = None
if args.filter:
try:
event_filter = {EventType(f) for f in args.filter.split(",")}
except ValueError as e:
sys.stderr.write(f"Invalid filter: {e}\n")
return 1
fmt = getattr(args, "format", "terminal") or "terminal"
# --diff: side-by-side HTML diff viewer
diff_session_id = getattr(args, "diff", "") or ""
if diff_session_id:
from .replay import replay_to_html_diff
diff_full = store.find_session(diff_session_id) or diff_session_id
output_path = getattr(args, "output", "") or \
f"diff-{session_id[:8]}-vs-{diff_full[:8]}.html"
replay_to_html_diff(store, session_id, diff_full, output_path=output_path)
sys.stdout.write(f"Diff HTML written to {output_path}\n")
return 0
if fmt == "html":
from .replay import replay_to_html
output_path = getattr(args, "output", "") or f"session-{session_id[:12]}.html"
replay_to_html(store, session_id, output_path=output_path)
sys.stdout.write(f"HTML replay written to {output_path}\n")
return 0
replay_session(
store=store,
session_id=session_id,
event_filter=event_filter,
speed=args.speed,
live=args.live,
limit=getattr(args, "limit", None),
)
return 0
def cmd_list(args: argparse.Namespace) -> int:
"""List all recorded sessions."""
store = TraceStore(args.trace_dir)
list_sessions(store)
return 0
def cmd_inspect(args: argparse.Namespace) -> int:
"""Inspect a session: show full event data as JSON."""
store = TraceStore(args.trace_dir)
session_id = args.session_id
if not store.session_exists(session_id):
found = store.find_session(session_id)
if found:
session_id = found
else:
sys.stderr.write(f"Session not found: {session_id}\n")
return 1
meta = store.load_meta(session_id)
events = store.load_events(session_id)
output = {
"session": json.loads(meta.to_json()),
"events": [json.loads(e.to_json()) for e in events],
}
sys.stdout.write(json.dumps(output, indent=2) + "\n")
return 0
def cmd_export(args: argparse.Namespace) -> int:
"""Export a session to JSON, CSV, or OTLP."""
# Route to Langfuse/OTLP export when --scores, --metrics, or --backend is set
if getattr(args, "scores", False) or getattr(args, "metrics", False) or getattr(args, "backend", None):
return cmd_export_scores(args)
# Route to anonymized export when --anonymize is set
if getattr(args, "anonymize", False):
return cmd_anonymize_export(args)
if getattr(args, "format", "") == "eu-ai-act":
return cmd_export_eu_ai_act(args)
store = TraceStore(args.trace_dir)
session_id = args.session_id
if not session_id:
session_id = store.get_latest_session_id()
if not session_id:
sys.stderr.write("No sessions found.\n")
return 1
elif not store.session_exists(session_id):
found = store.find_session(session_id)
if found:
session_id = found
else:
sys.stderr.write(f"Session not found: {session_id}\n")
return 1
events = store.load_events(session_id)
if args.format == "json":
output = [json.loads(e.to_json()) for e in events]
sys.stdout.write(json.dumps(output, indent=2) + "\n")
elif args.format == "csv":
writer = csv.writer(sys.stdout)
writer.writerow(["timestamp", "event_type", "event_id", "parent_id", "duration_ms", "data"])
for e in events:
writer.writerow([
e.timestamp,
e.event_type.value,
e.event_id,
e.parent_id,
e.duration_ms or "",
json.dumps(e.data),
])
elif args.format == "ndjson":
for e in events:
sys.stdout.write(e.to_json() + "\n")
elif args.format in ("otlp", "otlp-genai"):
from .otlp import export_otlp, session_to_otlp, session_to_otlp_genai
use_genai = args.format == "otlp-genai"
endpoint = args.endpoint
# When --endpoint is set and format is plain otlp, default to otlp-genai
# for better backend compatibility (backwards-compat: explicit --format otlp
# always uses the legacy mapping)
if endpoint and not use_genai:
use_genai = False # explicit --format otlp keeps legacy behaviour
if not endpoint:
# No endpoint: write OTLP JSON to --output file or stdout
meta = store.load_meta(session_id)
if use_genai:
payload = session_to_otlp_genai(meta, events, service_name=args.service_name)
else:
payload = session_to_otlp(meta, events, service_name=args.service_name)
output_path = getattr(args, "output", "") or ""
if not output_path:
fmt_suffix = "otlp-genai" if use_genai else "otlp"
output_path = f"trace-{session_id[:12]}-{fmt_suffix}.json"
with open(output_path, "w") as f:
f.write(json.dumps(payload, indent=2) + "\n")
sys.stderr.write(f"OTLP payload written to {output_path}\n")
sys.stderr.write(f"Send to a collector: agent-strace export --format {args.format} --endpoint <url>\n")
return 0
# Build headers from --header flags
headers = {}
for h in (args.header or []):
if ":" in h:
key, val = h.split(":", 1)
headers[key.strip()] = val.strip()
if use_genai:
# Export using GenAI conventions
import urllib.request, urllib.error
meta = store.load_meta(session_id)
payload = session_to_otlp_genai(meta, events, service_name=args.service_name)
body = json.dumps(payload).encode("utf-8")
url = endpoint.rstrip("/") + "/v1/traces"
req_headers = {"Content-Type": "application/json"}
req_headers.update(headers)
req = urllib.request.Request(url, data=body, headers=req_headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=30) as resp:
ok = resp.status in (200, 202)
sys.stderr.write(f"Exported {len(events)} events to {url} (HTTP {resp.status})\n")
return 0 if ok else 1
except Exception as exc:
sys.stderr.write(f"OTLP GenAI export failed: {exc}\n")
return 1
else:
ok = export_otlp(
store=store,
session_id=session_id,
endpoint=endpoint,
headers=headers,
service_name=args.service_name,
)
return 0 if ok else 1
return 0
def cmd_verify(args: argparse.Namespace) -> int:
"""Verify a session hash chain or an exported EU AI Act package."""
if getattr(args, "from_export", ""):
return cmd_verify_export(args)
store = TraceStore(args.trace_dir)
session_id = getattr(args, "session_id", None) or store.get_latest_session_id()
if not session_id:
sys.stderr.write("No sessions found.\n")
return 1
full_id = store.find_session(session_id) or session_id
if not store.session_exists(full_id):
sys.stderr.write(f"Session not found: {session_id}\n")
return 1
result = verify_chain(store, full_id)
if getattr(args, "format", "text") == "json":
sys.stdout.write(json.dumps({
"session_id": result.session_id,
"ok": result.ok,
"total_events": result.total_events,
"broken_at": result.broken_at,
"broken_event_id": result.broken_event_id,
}, indent=2) + "\n")
else:
result.format(sys.stdout)
return 0 if result.ok else 1
def cmd_stats(args: argparse.Namespace) -> int:
"""Show statistics for a session."""
if getattr(args, "include_subagents", False):
return cmd_stats_tree(args)
store = TraceStore(args.trace_dir)
session_id = args.session_id
if not session_id:
session_id = store.get_latest_session_id()
if not session_id:
sys.stderr.write("No sessions found.\n")
return 1
if not store.session_exists(session_id):
found = store.find_session(session_id)
if found:
session_id = found
else:
sys.stderr.write(f"Session not found: {session_id}\n")
return 1
events = store.load_events(session_id)
meta = store.load_meta(session_id)
# tool call frequency
tool_counts: dict[str, int] = {}
tool_durations: dict[str, list[float]] = {}
result_events = {e.parent_id: e for e in events if e.event_type == EventType.TOOL_RESULT}
for e in events:
if e.event_type == EventType.TOOL_CALL:
name = e.data.get("tool_name", "unknown")
tool_counts[name] = tool_counts.get(name, 0) + 1
# find matching result
result = result_events.get(e.event_id)
if result and result.duration_ms:
tool_durations.setdefault(name, []).append(result.duration_ms)
print(format_summary(meta))
print()
if tool_counts:
print(f" Tool Call Frequency:")
for name, count in sorted(tool_counts.items(), key=lambda x: -x[1]):
avg_ms = ""
if name in tool_durations:
durations = tool_durations[name]
avg = sum(durations) / len(durations)
avg_ms = f" avg: {avg:.0f}ms"
print(f" {name:<30} {count:>4}x{avg_ms}")
# error summary
errors = [e for e in events if e.event_type == EventType.ERROR]
if errors:
print(f"\n Errors ({len(errors)}):")
for e in errors:
msg = e.data.get("message", "unknown")
print(f" {msg[:80]}")
print()
return 0
def _hook_command_prefix(args: argparse.Namespace, provider: str = "claude") -> str:
redact_env = ""
if args.no_redact:
redact_env = "AGENT_TRACE_NO_REDACT=1 "
elif args.redact:
redact_env = "AGENT_TRACE_REDACT=1 "
provider_arg = "" if provider == "claude" else f"--provider {provider} "
return f"{redact_env}agent-strace hook {provider_arg}".rstrip()
def _claude_hooks_config(args: argparse.Namespace) -> dict:
cmd_prefix = _hook_command_prefix(args, provider="claude")
config = {
"hooks": {
"UserPromptSubmit": [{
"hooks": [{"type": "command", "command": f"{cmd_prefix} user-prompt"}],
}],
"PreToolUse": [{
"matcher": "",
"hooks": [{"type": "command", "command": f"{cmd_prefix} pre-tool"}],
}],
"PostToolUse": [{
"matcher": "",
"hooks": [{"type": "command", "command": f"{cmd_prefix} post-tool"}],
}],
"PostToolUseFailure": [{
"matcher": "",
"hooks": [{"type": "command", "command": f"{cmd_prefix} post-tool-failure"}],
}],
"Stop": [{
"hooks": [{"type": "command", "command": f"{cmd_prefix} stop"}],
}],
"SessionStart": [{
"hooks": [{"type": "command", "command": f"{cmd_prefix} session-start"}],
}],
"SessionEnd": [{
"hooks": [{"type": "command", "command": f"{cmd_prefix} session-end"}],
}],
}
}
return config
def _codex_hooks_config(args: argparse.Namespace) -> dict:
cmd_prefix = _hook_command_prefix(args, provider="codex")
return {
"hooks": {
"SessionStart": [{
"matcher": "startup|resume|clear|compact",
"hooks": [{
"type": "command",
"command": f"{cmd_prefix} session-start",
}],
}],
"UserPromptSubmit": [{
"hooks": [{
"type": "command",
"command": f"{cmd_prefix} user-prompt",
}],
}],
"PreToolUse": [{
"matcher": ".*",
"hooks": [{
"type": "command",
"command": f"{cmd_prefix} pre-tool",
}],
}],
"PostToolUse": [{
"matcher": ".*",
"hooks": [{
"type": "command",
"command": f"{cmd_prefix} post-tool",
}],
}],
"Stop": [{
"hooks": [{
"type": "command",
"command": f"{cmd_prefix} stop",
}],
}],
}
}
def _gemini_hooks_config(args: argparse.Namespace) -> dict:
cmd_prefix = _hook_command_prefix(args, provider="gemini")
return {
"hooks": {
"SessionStart": [{
"matcher": "*",
"hooks": [{
"name": "agent-strace-session-start",
"type": "command",
"command": f"{cmd_prefix} session-start",
"timeout": 5000,
}],
}],
"BeforeAgent": [{
"matcher": "*",
"hooks": [{
"name": "agent-strace-user-prompt",
"type": "command",
"command": f"{cmd_prefix} user-prompt",
"timeout": 5000,
}],
}],
"BeforeTool": [{
"matcher": "*",
"hooks": [{
"name": "agent-strace-tool-call",
"type": "command",
"command": f"{cmd_prefix} pre-tool",
"timeout": 5000,
}],
}],
"AfterTool": [{
"matcher": "*",
"hooks": [{
"name": "agent-strace-tool-result",
"type": "command",
"command": f"{cmd_prefix} post-tool",
"timeout": 5000,
}],
}],
"AfterAgent": [{
"matcher": "*",
"hooks": [{
"name": "agent-strace-assistant-response",
"type": "command",
"command": f"{cmd_prefix} stop",
"timeout": 5000,
}],
}],
"SessionEnd": [{
"matcher": "*",
"hooks": [{
"name": "agent-strace-session-end",
"type": "command",
"command": f"{cmd_prefix} session-end",
"timeout": 5000,
}],
}],
}
}
def _cursor_hooks_config(args: argparse.Namespace) -> dict:
cmd_prefix = _hook_command_prefix(args, provider="cursor")
return {
"version": 1,
"hooks": {
"sessionStart": [{
"type": "command",
"command": f"{cmd_prefix} session-start",
}],
"beforeSubmitPrompt": [{
"type": "command",
"command": f"{cmd_prefix} before-submit-prompt",
}],
"beforeShellExecution": [{
"type": "command",
"command": f"{cmd_prefix} before-shell-execution",
}],
"afterShellExecution": [{
"type": "command",
"command": f"{cmd_prefix} after-shell-execution",
}],
"afterFileEdit": [{
"type": "command",
"command": f"{cmd_prefix} after-file-edit",
}],
"afterAgentResponse": [{
"type": "command",
"command": f"{cmd_prefix} after-agent-response",
}],
"sessionEnd": [{
"type": "command",
"command": f"{cmd_prefix} session-end",
}],
},
}
def _gemini_extension_manifest() -> dict:
return {
"name": "agent-strace",
"version": __version__,
"description": "Capture and replay Gemini CLI sessions with agent-strace",
}
def _gemini_config_dir() -> Path:
return Path(os.environ.get("GEMINI_CONFIG_DIR", "~/.gemini")).expanduser()
def _write_gemini_extension(args: argparse.Namespace) -> tuple[Path, Path]:
extension_dir = _gemini_config_dir() / "extensions" / "agent-strace"
hooks_dir = extension_dir / "hooks"
hooks_dir.mkdir(parents=True, exist_ok=True)
manifest_path = extension_dir / "gemini-extension.json"
hooks_path = hooks_dir / "hooks.json"
manifest_path.write_text(json.dumps(_gemini_extension_manifest(), indent=2) + "\n")
hooks_path.write_text(json.dumps(_gemini_hooks_config(args), indent=2) + "\n")
return manifest_path, hooks_path
def _cursor_config_dir() -> Path:
return Path(os.environ.get("CURSOR_CONFIG_DIR", ".cursor")).expanduser()
def _write_cursor_hooks_config(args: argparse.Namespace) -> Path:
config_dir = _cursor_config_dir()
config_dir.mkdir(parents=True, exist_ok=True)
hooks_path = config_dir / "hooks.json"
hooks_path.write_text(json.dumps(_cursor_hooks_config(args), indent=2) + "\n")
return hooks_path
def cmd_setup(args: argparse.Namespace) -> None:
"""Generate hooks configuration for supported agent CLIs."""
cli = getattr(args, "cli", "claude") or "claude"
configs: list[tuple[str, str, dict]] = []
if cli in ("claude", "all"):
configs.append(("Claude Code", "~/.claude/settings.json", _claude_hooks_config(args)))
if cli in ("codex", "all"):
configs.append(("OpenAI Codex", "~/.codex/hooks.json", _codex_hooks_config(args)))
if cli in ("gemini", "all"):
manifest_path, hooks_path = _write_gemini_extension(args)
sys.stderr.write(
f"Wrote Gemini CLI extension manifest: {manifest_path}\n"
f"Wrote Gemini CLI hooks config: {hooks_path}\n"
)
if cli in ("cursor", "all"):
hooks_path = _write_cursor_hooks_config(args)
sys.stderr.write(f"Wrote Cursor hooks config: {hooks_path}\n")
for idx, (name, path, config) in enumerate(configs):
if idx:
sys.stdout.write("\n")
sys.stderr.write(f"Add this to {path} for {name}:\n\n")
sys.stdout.write(json.dumps(config, indent=2) + "\n")
if cli == "gemini":
sys.stdout.write(json.dumps(_gemini_hooks_config(args), indent=2) + "\n")
if cli == "cursor":
sys.stdout.write(json.dumps(_cursor_hooks_config(args), indent=2) + "\n")
sys.stderr.write(
"\nThis captures hook-visible agent sessions: user prompts, assistant "
"responses, and tool calls or edits exposed by the provider.\n"
"For Cursor, MCP proxy tracing still captures MCP calls; native hooks "
"capture only the prompt, shell, file-edit, and response events Cursor emits.\n"
"Replay with: agent-strace replay\n"
)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="agent-strace",
description="strace for AI agents. Capture and replay every tool call.",
)
parser.add_argument("--version", action="version", version=f"agent-strace {__version__}")
parser.add_argument(
"--trace-dir",
default=".agent-traces",
help="directory to store traces (default: .agent-traces)",
)
sub = parser.add_subparsers(dest="command")
# record
p_record = sub.add_parser("record", help="record an MCP server session (stdio)")
p_record.add_argument("--name", "-n", help="name for this agent/session")
record_redaction = p_record.add_mutually_exclusive_group()
record_redaction.add_argument(
"--redact",
action="store_true",
help="redact secrets from trace data (default)",
)
record_redaction.add_argument(
"--no-redact",
action="store_true",
help="disable automatic secret redaction",
)
p_record.add_argument("--verbose", "-v", action="store_true", help="print events to stderr during recording")
p_record.add_argument("--quiet", "-q", action="store_true", help="suppress all output except errors")
p_record.add_argument("--parent", metavar="SESSION",
help="parent session ID for subagent correlation")
p_record.add_argument("server_cmd", nargs=argparse.REMAINDER, help="MCP server command to run")
# record-http
p_record_http = sub.add_parser("record-http", help="record a remote MCP server session (HTTP/SSE)")
p_record_http.add_argument("--url", "-u", required=True, help="remote MCP server URL")
p_record_http.add_argument("--port", "-p", type=int, default=5100, help="local proxy port (default: 5100)")
p_record_http.add_argument("--name", "-n", help="name for this agent/session")
record_http_redaction = p_record_http.add_mutually_exclusive_group()
record_http_redaction.add_argument(
"--redact",
action="store_true",
help="redact secrets from trace data (default)",
)
record_http_redaction.add_argument(
"--no-redact",
action="store_true",
help="disable automatic secret redaction",
)
p_record_http.add_argument("--verbose", "-v", action="store_true", help="print events to stderr during recording")
p_record_http.add_argument("--quiet", "-q", action="store_true", help="suppress all output except errors")
p_record_http.add_argument("--parent", metavar="SESSION",
help="parent session ID for subagent correlation")
# replay
p_replay = sub.add_parser("replay", help="replay a recorded session")
p_replay.add_argument("session_id", nargs="?", help="session ID (default: latest)")
p_replay.add_argument("--filter", "-f", help="comma-separated event types to show")
p_replay.add_argument("--speed", "-s", type=float, default=0, help="replay speed multiplier (0=instant)")
p_replay.add_argument("--live", "-l", action="store_true", help="replay with timing delays")
p_replay.add_argument("--limit", "-n", type=int, default=None, metavar="N",
help="cap output at N events (default: all); useful for quick inspection of large sessions")
p_replay.add_argument("--format", choices=["terminal", "html"], default="terminal",
help="output format: terminal timeline or self-contained HTML viewer (default: terminal)")
p_replay.add_argument("--diff", metavar="SESSION_B",
help="generate side-by-side HTML diff against SESSION_B")
p_replay.add_argument("--output", "-o", default="",
help="output file path for --format html (default: session-<id>.html)")
p_replay.add_argument("--expand-subagents", action="store_true",
help="inline subagent sessions under their parent tool_call")
p_replay.add_argument("--tree", action="store_true",
help="show session hierarchy tree without full event replay")
# tree
p_tree = sub.add_parser("tree", help="show a parent/child session hierarchy")
p_tree.add_argument("session_id", nargs="?", help="root session ID or prefix (default: latest)")
p_tree.add_argument("--format", choices=["text", "json"], default="text",
help="output format (default: text)")
# list
sub.add_parser("list", help="list all recorded sessions")
# inspect
p_inspect = sub.add_parser("inspect", help="inspect a session as raw JSON")
p_inspect.add_argument("session_id", help="session ID or prefix")
# export
p_export = sub.add_parser("export", help="export a session")
p_export.add_argument("session_id", nargs="?", help="session ID or prefix")
p_export.add_argument("--format", choices=["json", "csv", "ndjson", "otlp", "otlp-genai", "eu-ai-act"],
default="json",
help="output format (otlp-genai uses strict OTel GenAI semantic conventions)")
p_export.add_argument("--endpoint", help="OTLP collector URL (e.g. http://localhost:4318)")
p_export.add_argument("--header", action="append", help="HTTP header for OTLP (e.g. 'x-honeycomb-team: KEY')")
p_export.add_argument("--service-name", default="agent-trace", help="OTel service name (default: agent-trace)")
# Langfuse / OTLP metrics flags
p_export.add_argument("--scores", action="store_true",
help="include eval scores in export")
p_export.add_argument("--metrics", action="store_true",
help="export behavioral metrics as OTLP gauges")
p_export.add_argument("--backend", choices=["langfuse", "otlp"],
help="export backend: langfuse or otlp")
p_export.add_argument("--since", metavar="Nd",
help="export sessions from the last N days (e.g. 7d)")
p_export.add_argument("--until", metavar="DATE",
help="upper time bound for batch exports (ISO date or timestamp)")
p_export.add_argument("--all", action="store_true",
help="export all sessions in the selected time window")
p_export.add_argument("--langfuse-public-key", dest="langfuse_public_key", metavar="KEY",
help="Langfuse public key (overrides LANGFUSE_PUBLIC_KEY)")
p_export.add_argument("--langfuse-secret-key", dest="langfuse_secret_key", metavar="KEY",
help="Langfuse secret key (overrides LANGFUSE_SECRET_KEY)")
p_export.add_argument("--langfuse-host", dest="langfuse_host", metavar="URL",
help="Langfuse host (default: https://cloud.langfuse.com)")
p_export.add_argument("--otlp-endpoint", dest="otlp_endpoint", metavar="URL",
help="OTLP metrics endpoint (overrides OTEL_EXPORTER_OTLP_ENDPOINT)")
p_export.add_argument("--otlp-headers", dest="otlp_headers", metavar="HEADERS",
help="OTLP headers as key=value,key=value")
p_export.add_argument("--anonymize", action="store_true",
help="strip identifying information (paths, hostnames, emails, usernames) from the export")
p_export.add_argument("--anonymize-config", dest="anonymize_config", metavar="FILE",
help="path to custom anonymization rules YAML file")
p_export.add_argument("--output", "-o", default="",
help="output file path")
p_export.add_argument("--dry-run", action="store_true",
help="show what would be anonymized without writing output (use with --anonymize)")
# stats
p_stats = sub.add_parser("stats", help="show session statistics")
p_stats.add_argument("session_id", nargs="?", help="session ID (default: latest)")
p_stats.add_argument("--include-subagents", action="store_true",
help="roll up stats across all subagent sessions")
# hook (called by agent CLI hooks systems)
p_hook = sub.add_parser("hook", help="handle an agent CLI hook event (internal)")
p_hook.add_argument("--provider", choices=["claude", "codex", "gemini", "cursor"], default="claude",
help="hook provider (default: claude)")
p_hook.add_argument("event", nargs="?", help="hook event: session-start, session-end, pre-tool, post-tool, post-tool-failure")
# setup (generate agent CLI hooks config)
p_setup = sub.add_parser("setup", help="generate agent CLI hooks configuration")
setup_redaction = p_setup.add_mutually_exclusive_group()
setup_redaction.add_argument(
"--redact",
action="store_true",
help="enable secret redaction explicitly (default)",
)
setup_redaction.add_argument(
"--no-redact",
action="store_true",
help="disable automatic secret redaction in generated hooks",
)
p_setup.add_argument("--global", dest="global_config", action="store_true", help="output config for ~/.claude/settings.json (all projects)")
p_setup.add_argument("--cli", choices=["claude", "codex", "gemini", "cursor", "all"], default="claude",
help="agent CLI to configure (default: claude)")
# import (Claude Code JSONL session logs)
p_import = sub.add_parser("import", help="import a Claude Code JSONL session log")
p_import.add_argument("path", nargs="?", help="path to .jsonl session file")
p_import.add_argument("--discover", action="store_true", help="list available Claude Code sessions")
p_import.add_argument("--claude-dir", default="~/.claude", help="Claude config directory (default: ~/.claude)")
# explain
p_explain = sub.add_parser("explain", help="explain a session in plain English")
p_explain.add_argument("session_id", nargs="?", help="session ID or prefix (default: latest)")
# timeline
p_timeline = sub.add_parser("timeline",
help="structured chronological view of a session by phase")
p_timeline.add_argument("session_id", nargs="?",
help="session ID or prefix (default: latest)")
p_timeline.add_argument("--model", default="sonnet",
choices=["sonnet", "opus", "haiku", "gpt4", "gpt4o"],
help="model pricing for cost estimates (default: sonnet)")
p_timeline.add_argument("--format", choices=["text", "json"], default="text",
help="output format (default: text)")
# diff
p_diff = sub.add_parser("diff", help="compare two sessions structurally")
p_diff.add_argument("session_a", help="first session ID or prefix")
p_diff.add_argument("session_b", help="second session ID or prefix")
# why
p_why = sub.add_parser("why", help="trace the causal chain for a specific event")
p_why.add_argument("session_id", nargs="?", help="session ID or prefix (default: latest)")
p_why.add_argument("event_number", type=int, help="1-based event number (from replay output)")
# cost
p_cost = sub.add_parser("cost", help="estimate token cost for a session")
p_cost.add_argument("session_id", nargs="?", help="session ID or prefix (default: latest)")
p_cost.add_argument("--model", default="sonnet",
choices=["sonnet", "opus", "haiku", "gpt4", "gpt4o"],
help="model pricing to use (default: sonnet)")
p_cost.add_argument("--input-price", type=float, dest="input_price",
help="custom input price per 1M tokens (overrides --model)")
p_cost.add_argument("--output-price", type=float, dest="output_price",
help="custom output price per 1M tokens (overrides --model)")
# audit
p_audit = sub.add_parser("audit", help="check session tool calls against a policy file")
p_audit.add_argument("session_id", nargs="?", help="session ID or prefix (default: latest)")
p_audit.add_argument("--verify-chain", dest="verify_chain", action="store_true",
help="verify SHA-256 hash chain integrity before policy audit")
p_audit.add_argument("--policy", default=".agent-scope.json",