agent-token-forensics 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.
@@ -0,0 +1,28 @@
1
+ """Read-only JSONL token & prompt-cache burn forensics for AI coding agents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ from agent_token_forensics.analyzer import (
8
+ DEFAULT_PRICING_PER_M,
9
+ analyze_files,
10
+ analyze_turns,
11
+ format_markdown,
12
+ format_text,
13
+ )
14
+ from agent_token_forensics.cli import main
15
+ from agent_token_forensics.parser import TurnRecord, collect_jsonl_files, parse_jsonl_file
16
+
17
+ __all__ = [
18
+ "DEFAULT_PRICING_PER_M",
19
+ "TurnRecord",
20
+ "__version__",
21
+ "analyze_files",
22
+ "analyze_turns",
23
+ "collect_jsonl_files",
24
+ "format_markdown",
25
+ "format_text",
26
+ "main",
27
+ "parse_jsonl_file",
28
+ ]
@@ -0,0 +1,10 @@
1
+ """Module entrypoint for `python -m agent_token_forensics`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from agent_token_forensics.cli import main
8
+
9
+ if __name__ == "__main__":
10
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,269 @@
1
+ """Token burn, prompt-cache busting, compaction inflection, and retry-loop forensics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from collections.abc import Iterable
7
+ from typing import Any
8
+
9
+ from agent_token_forensics.parser import TurnRecord, collect_jsonl_entries, parse_jsonl_file
10
+
11
+ # Indicative USD per 1M tokens: (input, output, cache_read, cache_write)
12
+ DEFAULT_PRICING_PER_M: dict[str, tuple[float, float, float, float]] = {
13
+ "opus": (15.0, 75.0, 1.5, 18.75),
14
+ "sonnet": (3.0, 15.0, 0.3, 3.75),
15
+ "haiku": (0.8, 4.0, 0.08, 1.0),
16
+ "gpt-4o": (2.5, 10.0, 1.25, 2.5),
17
+ "codex": (2.0, 8.0, 0.5, 2.0),
18
+ "o3": (2.0, 8.0, 0.5, 2.0),
19
+ "gemini": (1.25, 10.0, 0.31, 1.25),
20
+ "default": (3.0, 15.0, 0.3, 3.75),
21
+ }
22
+
23
+
24
+ def resolve_pricing(
25
+ model: str,
26
+ pricing: dict[str, tuple[float, float, float, float]] | None = None,
27
+ ) -> tuple[float, float, float, float]:
28
+ table = pricing or DEFAULT_PRICING_PER_M
29
+ low = model.lower()
30
+ for key, rates in table.items():
31
+ if key != "default" and key in low:
32
+ return rates
33
+ return table.get("default", DEFAULT_PRICING_PER_M["default"])
34
+
35
+
36
+ def estimate_turn_cost(
37
+ turn: TurnRecord,
38
+ pricing: dict[str, tuple[float, float, float, float]] | None = None,
39
+ ) -> float:
40
+ in_r, out_r, cr_r, cw_r = resolve_pricing(turn.model, pricing)
41
+ return (
42
+ turn.input_tokens * in_r
43
+ + turn.output_tokens * out_r
44
+ + turn.cache_read_tokens * cr_r
45
+ + turn.cache_write_tokens * cw_r
46
+ ) / 1_000_000.0
47
+
48
+
49
+ def analyze_turns(
50
+ turns: list[TurnRecord],
51
+ *,
52
+ compact_threshold: int = 80_000,
53
+ post_compact_target: int = 20_000,
54
+ loop_threshold: int = 3,
55
+ pricing: dict[str, tuple[float, float, float, float]] | None = None,
56
+ ) -> dict[str, Any]:
57
+ """Run full token, prompt-cache, compaction, and retry-loop forensics on normalized turns."""
58
+ if compact_threshold <= 0:
59
+ raise ValueError("compact_threshold must be positive")
60
+ if post_compact_target < 0:
61
+ raise ValueError("post_compact_target must be non-negative")
62
+
63
+ total_in = sum(t.input_tokens for t in turns)
64
+ total_out = sum(t.output_tokens for t in turns)
65
+ total_cr = sum(t.cache_read_tokens for t in turns)
66
+ total_cw = sum(t.cache_write_tokens for t in turns)
67
+ total_ctx = total_in + total_cr + total_cw
68
+ cache_hit_ratio = round(total_cr / total_ctx, 4) if total_ctx > 0 else 0.0
69
+ total_cost = round(sum(estimate_turn_cost(t, pricing) for t in turns), 4)
70
+
71
+ by_model: dict[str, dict[str, Any]] = {}
72
+ tool_tokens: dict[str, int] = defaultdict(int)
73
+ tool_calls: dict[str, int] = defaultdict(int)
74
+
75
+ for t in turns:
76
+ bucket = by_model.setdefault(
77
+ t.model,
78
+ {"turns": 0, "input_tokens": 0, "output_tokens": 0, "cache_read_tokens": 0, "est_usd": 0.0},
79
+ )
80
+ bucket["turns"] += 1
81
+ bucket["input_tokens"] += t.input_tokens
82
+ bucket["output_tokens"] += t.output_tokens
83
+ bucket["cache_read_tokens"] += t.cache_read_tokens
84
+ bucket["est_usd"] = round(bucket["est_usd"] + estimate_turn_cost(t, pricing), 4)
85
+ for tool in t.tools:
86
+ tool_calls[tool] += 1
87
+ tool_tokens[tool] += t.total_context + t.output_tokens
88
+
89
+ # Per-file sequential forensics: compaction inflection, cache busts, retry loops.
90
+ by_file: dict[str, list[TurnRecord]] = defaultdict(list)
91
+ for t in turns:
92
+ by_file[t.source_file].append(t)
93
+
94
+ cache_busts: list[dict[str, Any]] = []
95
+ retry_loops: list[dict[str, Any]] = []
96
+ compaction_recommendations: list[dict[str, Any]] = []
97
+ total_saveable_ctx = 0
98
+ total_saveable_usd = 0.0
99
+
100
+ for fname, fturns in sorted(by_file.items()):
101
+ prev_warm = False
102
+ first_over_idx: int | None = None
103
+ run_sig: tuple[str, ...] | None = None
104
+ run_len = 0
105
+ run_start = 0
106
+
107
+ for pos, t in enumerate(fturns):
108
+ ctx = t.total_context
109
+ ratio = t.cache_hit_ratio
110
+ if prev_warm and ctx >= 10_000 and ratio < 0.30:
111
+ cache_busts.append(
112
+ {
113
+ "file": fname,
114
+ "turn": t.turn_index,
115
+ "line": t.line_number,
116
+ "context_tokens": ctx,
117
+ "cache_hit_ratio": round(ratio, 3),
118
+ }
119
+ )
120
+ prev_warm = ctx >= 10_000 and ratio >= 0.70
121
+
122
+ if first_over_idx is None and ctx >= compact_threshold:
123
+ first_over_idx = pos
124
+
125
+ sig = t.tools
126
+ if sig and sig == run_sig:
127
+ run_len += 1
128
+ else:
129
+ if run_sig and run_len >= loop_threshold:
130
+ retry_loops.append(
131
+ {
132
+ "file": fname,
133
+ "start_turn": run_start,
134
+ "repeats": run_len,
135
+ "tools": list(run_sig),
136
+ }
137
+ )
138
+ run_sig = sig if sig else None
139
+ run_len = 1 if sig else 0
140
+ run_start = t.turn_index
141
+
142
+ if run_sig and run_len >= loop_threshold:
143
+ retry_loops.append(
144
+ {
145
+ "file": fname,
146
+ "start_turn": run_start,
147
+ "repeats": run_len,
148
+ "tools": list(run_sig),
149
+ }
150
+ )
151
+
152
+ if first_over_idx is not None:
153
+ tail = fturns[first_over_idx + 1 :]
154
+ if tail:
155
+ excess_ctx = sum(max(0, t.total_context - post_compact_target) for t in tail)
156
+ tail_cost = sum(estimate_turn_cost(t, pricing) for t in tail)
157
+ tail_ctx = sum(t.total_context for t in tail)
158
+ save_frac = (excess_ctx / tail_ctx) if tail_ctx > 0 else 0.0
159
+ est_usd_saved = round(tail_cost * save_frac * 0.85, 4)
160
+ total_saveable_ctx += excess_ctx
161
+ total_saveable_usd += est_usd_saved
162
+ inflection = fturns[first_over_idx]
163
+ compaction_recommendations.append(
164
+ {
165
+ "file": fname,
166
+ "compact_after_turn": inflection.turn_index,
167
+ "context_at_inflection": inflection.total_context,
168
+ "tail_turns": len(tail),
169
+ "saveable_context_tokens": excess_ctx,
170
+ "est_savings_usd": est_usd_saved,
171
+ }
172
+ )
173
+
174
+ est_savings_pct = round((total_saveable_ctx / total_ctx) * 100.0, 1) if total_ctx > 0 else 0.0
175
+ top_tools = [
176
+ {"tool": name, "calls": tool_calls[name], "attributed_tokens": tok}
177
+ for name, tok in sorted(tool_tokens.items(), key=lambda kv: (-kv[1], kv[0]))[:10]
178
+ ]
179
+
180
+ return {
181
+ "files_analyzed": len(by_file),
182
+ "turns": len(turns),
183
+ "uncached_input_tokens": total_in,
184
+ "output_tokens": total_out,
185
+ "cache_read_tokens": total_cr,
186
+ "cache_write_tokens": total_cw,
187
+ "total_context_tokens": total_ctx,
188
+ "cache_hit_ratio": cache_hit_ratio,
189
+ "estimated_cost_usd": total_cost,
190
+ "compact_threshold": compact_threshold,
191
+ "estimated_compaction_savings_pct": est_savings_pct,
192
+ "estimated_compaction_savings_usd": round(total_saveable_usd, 4),
193
+ "cache_bust_events": cache_busts,
194
+ "retry_loops": retry_loops,
195
+ "compaction_recommendations": compaction_recommendations,
196
+ "top_tools_by_tokens": top_tools,
197
+ "by_model": by_model,
198
+ }
199
+
200
+
201
+ def analyze_files(
202
+ raw_paths: Iterable[str],
203
+ *,
204
+ compact_threshold: int = 80_000,
205
+ post_compact_target: int = 20_000,
206
+ loop_threshold: int = 3,
207
+ pricing: dict[str, tuple[float, float, float, float]] | None = None,
208
+ ) -> dict[str, Any]:
209
+ entries = collect_jsonl_entries(raw_paths)
210
+ all_turns: list[TurnRecord] = []
211
+ for fpath, source_label in entries:
212
+ all_turns.extend(parse_jsonl_file(fpath, source_label=source_label))
213
+ return analyze_turns(
214
+ all_turns,
215
+ compact_threshold=compact_threshold,
216
+ post_compact_target=post_compact_target,
217
+ loop_threshold=loop_threshold,
218
+ pricing=pricing,
219
+ )
220
+
221
+
222
+ def format_text(report: dict[str, Any]) -> str:
223
+ lines = [
224
+ "=== Agent Token & Quota Burn Forensics ===",
225
+ f"Files: {report['files_analyzed']} | Turns: {report['turns']} | "
226
+ f"Est. Cost: ${report['estimated_cost_usd']:.4f}",
227
+ f"Context Tokens: {report['total_context_tokens']:,} "
228
+ f"(cache_read={report['cache_read_tokens']:,}, uncached={report['uncached_input_tokens']:,}, "
229
+ f"hit_ratio={report['cache_hit_ratio'] * 100:.1f}%)",
230
+ f"Output Tokens: {report['output_tokens']:,}",
231
+ f"Estimated Compaction Savings (threshold={report['compact_threshold']:,}): "
232
+ f"{report['estimated_compaction_savings_pct']:.1f}% (~${report['estimated_compaction_savings_usd']:.4f})",
233
+ f"Cache Busts Detected: {len(report['cache_bust_events'])} | Retry Loops: {len(report['retry_loops'])}",
234
+ ]
235
+ if report["compaction_recommendations"]:
236
+ lines.append("\nCompaction Inflection Points:")
237
+ for rec in report["compaction_recommendations"][:5]:
238
+ lines.append(
239
+ f" - {rec['file']}: compact after turn {rec['compact_after_turn']} "
240
+ f"(ctx={rec['context_at_inflection']:,}, tail={rec['tail_turns']} turns, "
241
+ f"saveable={rec['saveable_context_tokens']:,} tok)"
242
+ )
243
+ if report["retry_loops"]:
244
+ lines.append("\nRetry Loops Detected:")
245
+ for lp in report["retry_loops"][:5]:
246
+ lines.append(
247
+ f" - {lp['file']} turn {lp['start_turn']}: {lp['repeats']}x repeated {lp['tools']}"
248
+ )
249
+ return "\n".join(lines)
250
+
251
+
252
+ def format_markdown(report: dict[str, Any]) -> str:
253
+ lines = [
254
+ "# Agent Token & Quota Burn Forensics",
255
+ "",
256
+ "| Metric | Value |",
257
+ "|---|---:|",
258
+ f"| Files analyzed | {report['files_analyzed']} |",
259
+ f"| Model turns | {report['turns']} |",
260
+ f"| Total context tokens | {report['total_context_tokens']:,} |",
261
+ f"| Prompt cache hit ratio | {report['cache_hit_ratio'] * 100:.1f}% |",
262
+ f"| Output tokens | {report['output_tokens']:,} |",
263
+ f"| Estimated cost | ${report['estimated_cost_usd']:.4f} |",
264
+ f"| Est. compaction savings | {report['estimated_compaction_savings_pct']:.1f}% "
265
+ f"(${report['estimated_compaction_savings_usd']:.4f}) |",
266
+ f"| Cache bust events | {len(report['cache_bust_events'])} |",
267
+ f"| Retry loops | {len(report['retry_loops'])} |",
268
+ ]
269
+ return "\n".join(lines)
@@ -0,0 +1,55 @@
1
+ """CLI for `agent-token-forensics`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ from agent_token_forensics.analyzer import analyze_files, format_markdown, format_text
10
+
11
+
12
+ def build_parser() -> argparse.ArgumentParser:
13
+ parser = argparse.ArgumentParser(
14
+ prog="agent-token-forensics",
15
+ description="Read-only JSONL token & prompt-cache burn forensics for AI coding agents.",
16
+ )
17
+ sub = parser.add_subparsers(dest="cmd", required=True)
18
+ pa = sub.add_parser("analyze", help="Analyze one or more JSONL transcript files or directories.")
19
+ pa.add_argument("paths", nargs="+", help="JSONL file(s) or directory path(s) to scan read-only.")
20
+ pa.add_argument("--compact-threshold", type=int, default=80_000)
21
+ pa.add_argument("--post-compact-target", type=int, default=20_000)
22
+ pa.add_argument("--loop-threshold", type=int, default=3)
23
+ pa.add_argument("--json", action="store_true", help="Emit JSON output.")
24
+ pa.add_argument("--markdown", action="store_true", help="Emit Markdown summary table.")
25
+ sub.add_parser(
26
+ "mcp-serve",
27
+ help="Run the strictly read-only MCP JSON-RPC 2.0 server over stdio.",
28
+ )
29
+ return parser
30
+
31
+
32
+ def main(argv: list[str] | None = None) -> int:
33
+ args = build_parser().parse_args(argv)
34
+ if args.cmd == "mcp-serve":
35
+ from agent_token_forensics.mcp_server import run_stdio
36
+
37
+ return run_stdio()
38
+ try:
39
+ report = analyze_files(
40
+ args.paths,
41
+ compact_threshold=args.compact_threshold,
42
+ post_compact_target=args.post_compact_target,
43
+ loop_threshold=args.loop_threshold,
44
+ )
45
+ except (FileNotFoundError, OSError, ValueError) as exc:
46
+ print(f"agent-token-forensics error: {exc}", file=sys.stderr)
47
+ return 2
48
+
49
+ if args.json:
50
+ print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
51
+ elif args.markdown:
52
+ print(format_markdown(report))
53
+ else:
54
+ print(format_text(report))
55
+ return 0
@@ -0,0 +1,325 @@
1
+ """Zero-dependency, strictly read-only MCP JSON-RPC 2.0 server over stdio."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any, TextIO
9
+
10
+ from agent_token_forensics import __version__
11
+ from agent_token_forensics.analyzer import analyze_files, format_markdown
12
+
13
+ JSONRPC_VERSION = "2.0"
14
+ DEFAULT_PROTOCOL_VERSION = "2024-11-05"
15
+ SERVER_NAME = "agent-token-forensics"
16
+
17
+ PARSE_ERROR = -32700
18
+ INVALID_REQUEST = -32600
19
+ METHOD_NOT_FOUND = -32601
20
+ INVALID_PARAMS = -32602
21
+
22
+ TOOLS: list[dict[str, Any]] = [
23
+ {
24
+ "name": "analyze_transcripts",
25
+ "description": (
26
+ "Strictly read-only analysis of a JSONL transcript file or directory. "
27
+ "Detects prompt-cache bust events, compaction inflection points, retry loops, "
28
+ "top tools by attributed tokens, and estimated USD cost/savings. "
29
+ "Performs zero writes and zero network calls."
30
+ ),
31
+ "inputSchema": {
32
+ "type": "object",
33
+ "properties": {
34
+ "path": {
35
+ "type": "string",
36
+ "description": "Path to a JSONL transcript file or directory of JSONL files.",
37
+ },
38
+ "compact_threshold": {
39
+ "type": "integer",
40
+ "description": "Context token threshold for compaction inflection detection.",
41
+ "default": 80_000,
42
+ "minimum": 1,
43
+ },
44
+ "post_compact_target": {
45
+ "type": "integer",
46
+ "description": "Target context tokens after compaction for savings estimation.",
47
+ "default": 20_000,
48
+ "minimum": 0,
49
+ },
50
+ "output_format": {
51
+ "type": "string",
52
+ "description": "Output format: 'json' for structured payload or 'markdown' for summary table.",
53
+ "enum": ["json", "markdown"],
54
+ "default": "json",
55
+ },
56
+ },
57
+ "required": ["path"],
58
+ "additionalProperties": False,
59
+ },
60
+ "annotations": {
61
+ "readOnlyHint": True,
62
+ "destructiveHint": False,
63
+ "idempotentHint": True,
64
+ "openWorldHint": False,
65
+ },
66
+ },
67
+ {
68
+ "name": "forensics_about",
69
+ "description": (
70
+ "Return server version, supported multi-vendor JSONL transcript schemas, "
71
+ "and strict read-only / zero-telemetry / zero-dependency guarantees."
72
+ ),
73
+ "inputSchema": {
74
+ "type": "object",
75
+ "properties": {},
76
+ "additionalProperties": False,
77
+ },
78
+ "annotations": {
79
+ "readOnlyHint": True,
80
+ "destructiveHint": False,
81
+ "idempotentHint": True,
82
+ "openWorldHint": False,
83
+ },
84
+ },
85
+ ]
86
+
87
+ SUPPORTED_TRANSCRIPT_SCHEMAS: list[dict[str, Any]] = [
88
+ {
89
+ "vendor": "Claude Code / Anthropic",
90
+ "fields": [
91
+ "usage.input_tokens",
92
+ "usage.output_tokens",
93
+ "usage.cache_read_input_tokens",
94
+ "usage.cache_creation_input_tokens",
95
+ ],
96
+ },
97
+ {
98
+ "vendor": "OpenAI / Codex / Cursor",
99
+ "fields": [
100
+ "usage.prompt_tokens",
101
+ "usage.completion_tokens",
102
+ "usage.prompt_tokens_details.cached_tokens",
103
+ ],
104
+ },
105
+ {
106
+ "vendor": "Gemini",
107
+ "fields": [
108
+ "usageMetadata.promptTokenCount",
109
+ "usageMetadata.candidatesTokenCount",
110
+ "usageMetadata.cachedContentTokenCount",
111
+ ],
112
+ },
113
+ {
114
+ "vendor": "Antigravity",
115
+ "fields": [
116
+ "input_tokens",
117
+ "output_tokens",
118
+ "cache_read_tokens",
119
+ "step_update.usage",
120
+ ],
121
+ },
122
+ ]
123
+
124
+
125
+ def _success_response(req_id: Any, result: dict[str, Any]) -> dict[str, Any]:
126
+ return {"jsonrpc": JSONRPC_VERSION, "id": req_id, "result": result}
127
+
128
+
129
+ def _error_response(req_id: Any, code: int, message: str) -> dict[str, Any]:
130
+ return {"jsonrpc": JSONRPC_VERSION, "id": req_id, "error": {"code": code, "message": message}}
131
+
132
+
133
+ def _tool_result(text: str, *, is_error: bool = False) -> dict[str, Any]:
134
+ return {"content": [{"type": "text", "text": text}], "isError": is_error}
135
+
136
+
137
+ def _validate_int_arg(arguments: dict[str, Any], key: str, default: int, *, minimum: int) -> int:
138
+ value = arguments.get(key)
139
+ if value is None:
140
+ return default
141
+ if isinstance(value, bool) or not isinstance(value, int):
142
+ raise ValueError(f"'{key}' must be an integer")
143
+ if value < minimum:
144
+ raise ValueError(f"'{key}' must be >= {minimum}")
145
+ return value
146
+
147
+
148
+ def _call_analyze_transcripts(arguments: dict[str, Any]) -> dict[str, Any]:
149
+ raw_path = arguments.get("path")
150
+ if not isinstance(raw_path, str) or not raw_path.strip():
151
+ return _tool_result(
152
+ json.dumps({"error": "'path' must be a non-empty string"}, ensure_ascii=False),
153
+ is_error=True,
154
+ )
155
+
156
+ try:
157
+ compact_threshold = _validate_int_arg(arguments, "compact_threshold", 80_000, minimum=1)
158
+ post_compact_target = _validate_int_arg(arguments, "post_compact_target", 20_000, minimum=0)
159
+ except ValueError as exc:
160
+ return _tool_result(json.dumps({"error": str(exc)}, ensure_ascii=False), is_error=True)
161
+
162
+ output_format = arguments.get("output_format", "json")
163
+ if output_format is None:
164
+ output_format = "json"
165
+ if not isinstance(output_format, str) or output_format not in {"json", "markdown"}:
166
+ return _tool_result(
167
+ json.dumps({"error": "'output_format' must be 'json' or 'markdown'"}, ensure_ascii=False),
168
+ is_error=True,
169
+ )
170
+
171
+ target = Path(raw_path).expanduser().absolute()
172
+ if not target.exists():
173
+ return _tool_result(
174
+ json.dumps({"error": f"path does not exist: {raw_path}"}, ensure_ascii=False),
175
+ is_error=True,
176
+ )
177
+
178
+ try:
179
+ report = analyze_files(
180
+ [str(target)],
181
+ compact_threshold=compact_threshold,
182
+ post_compact_target=post_compact_target,
183
+ )
184
+ except (FileNotFoundError, OSError, ValueError) as exc:
185
+ return _tool_result(json.dumps({"error": str(exc)}, ensure_ascii=False), is_error=True)
186
+
187
+ if output_format == "markdown":
188
+ return _tool_result(format_markdown(report))
189
+
190
+ payload: dict[str, Any] = {
191
+ **report,
192
+ "compaction_inflection_points": report["compaction_recommendations"],
193
+ "cost_summary": {
194
+ "estimated_cost_usd": report["estimated_cost_usd"],
195
+ "estimated_compaction_savings_pct": report["estimated_compaction_savings_pct"],
196
+ "estimated_compaction_savings_usd": report["estimated_compaction_savings_usd"],
197
+ "total_context_tokens": report["total_context_tokens"],
198
+ "cache_hit_ratio": report["cache_hit_ratio"],
199
+ },
200
+ "read_only": True,
201
+ }
202
+ return _tool_result(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True))
203
+
204
+
205
+ def _call_forensics_about() -> dict[str, Any]:
206
+ about = {
207
+ "name": SERVER_NAME,
208
+ "version": __version__,
209
+ "license": "MIT",
210
+ "repository": "https://github.com/BlackBadHope/agent-token-forensics",
211
+ "supported_transcript_schemas": SUPPORTED_TRANSCRIPT_SCHEMAS,
212
+ "guarantees": {
213
+ "read_only": True,
214
+ "zero_telemetry": True,
215
+ "zero_network_calls": True,
216
+ "zero_external_dependencies": True,
217
+ "python_stdlib_only": True,
218
+ },
219
+ "tools": [tool["name"] for tool in TOOLS],
220
+ }
221
+ return _tool_result(json.dumps(about, ensure_ascii=False, indent=2, sort_keys=True))
222
+
223
+
224
+ def handle_request(message: Any) -> dict[str, Any] | None:
225
+ """Process one decoded JSON-RPC 2.0 message and return a response dict or None for notifications."""
226
+ if not isinstance(message, dict):
227
+ return _error_response(None, INVALID_REQUEST, "Request must be a JSON object")
228
+
229
+ has_id = "id" in message
230
+ req_id = message.get("id")
231
+
232
+ if message.get("jsonrpc") != JSONRPC_VERSION:
233
+ return _error_response(req_id, INVALID_REQUEST, "Invalid or missing jsonrpc version; expected '2.0'")
234
+
235
+ method = message.get("method")
236
+ if not isinstance(method, str) or not method:
237
+ return _error_response(req_id, INVALID_REQUEST, "Missing or invalid 'method'")
238
+
239
+ params = message.get("params")
240
+ if params is not None and not isinstance(params, dict):
241
+ if not has_id:
242
+ return None
243
+ return _error_response(req_id, INVALID_PARAMS, "'params' must be a JSON object")
244
+ params_dict: dict[str, Any] = params if isinstance(params, dict) else {}
245
+
246
+ if method == "notifications/initialized" or not has_id:
247
+ return None
248
+
249
+ if method == "initialize":
250
+ client_version = params_dict.get("protocolVersion")
251
+ protocol_version = (
252
+ client_version.strip()
253
+ if isinstance(client_version, str) and client_version.strip()
254
+ else DEFAULT_PROTOCOL_VERSION
255
+ )
256
+ return _success_response(
257
+ req_id,
258
+ {
259
+ "protocolVersion": protocol_version,
260
+ "capabilities": {"tools": {}},
261
+ "serverInfo": {"name": SERVER_NAME, "version": __version__},
262
+ },
263
+ )
264
+
265
+ if method == "ping":
266
+ return _success_response(req_id, {})
267
+
268
+ if method == "tools/list":
269
+ return _success_response(req_id, {"tools": TOOLS})
270
+
271
+ if method == "tools/call":
272
+ tool_name = params_dict.get("name")
273
+ if not isinstance(tool_name, str) or not tool_name:
274
+ return _error_response(req_id, INVALID_PARAMS, "tools/call requires a non-empty string 'name'")
275
+ arguments = params_dict.get("arguments", {})
276
+ if arguments is None:
277
+ arguments = {}
278
+ if not isinstance(arguments, dict):
279
+ return _error_response(req_id, INVALID_PARAMS, "tools/call 'arguments' must be a JSON object")
280
+
281
+ if tool_name == "analyze_transcripts":
282
+ return _success_response(req_id, _call_analyze_transcripts(arguments))
283
+ if tool_name == "forensics_about":
284
+ return _success_response(req_id, _call_forensics_about())
285
+ return _error_response(req_id, INVALID_PARAMS, f"Unknown tool: {tool_name}")
286
+
287
+ return _error_response(req_id, METHOD_NOT_FOUND, f"Method not found: {method}")
288
+
289
+
290
+ def handle_line(raw_line: str) -> dict[str, Any] | None:
291
+ """Decode and dispatch one newline-delimited JSON-RPC 2.0 line."""
292
+ stripped = raw_line.strip()
293
+ if not stripped:
294
+ return None
295
+ try:
296
+ message = json.loads(stripped)
297
+ except json.JSONDecodeError as exc:
298
+ return _error_response(None, PARSE_ERROR, f"Parse error: {exc.msg}")
299
+ return handle_request(message)
300
+
301
+
302
+ def run_stdio(stdin: TextIO | None = None, stdout: TextIO | None = None) -> int:
303
+ """Run the newline-delimited JSON-RPC 2.0 MCP server loop on stdin/stdout."""
304
+ in_stream = stdin if stdin is not None else sys.stdin
305
+ out_stream = stdout if stdout is not None else sys.stdout
306
+ for raw_line in in_stream:
307
+ response = handle_line(raw_line)
308
+ if response is not None:
309
+ out_stream.write(json.dumps(response, ensure_ascii=False, separators=(",", ":")) + "\n")
310
+ out_stream.flush()
311
+ return 0
312
+
313
+
314
+ def main(argv: list[str] | None = None) -> int:
315
+ """Module entrypoint for `python -m agent_token_forensics.mcp_server`."""
316
+ args = sys.argv[1:] if argv is None else argv
317
+ if args and args[0] in {"-h", "--help"}:
318
+ sys.stderr.write("Usage: python -m agent_token_forensics.mcp_server\n")
319
+ sys.stderr.write("Runs the strictly read-only MCP JSON-RPC 2.0 server over stdio.\n")
320
+ return 0
321
+ return run_stdio()
322
+
323
+
324
+ if __name__ == "__main__":
325
+ raise SystemExit(main())
@@ -0,0 +1,276 @@
1
+ """Vendor-agnostic read-only JSONL transcript parser for AI coding agent logs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from collections.abc import Iterable
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ SKIP_DIRS = frozenset({".git", "__pycache__", "node_modules", ".venv", "venv"})
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class TurnRecord:
17
+ """Normalized token usage record for a single model invocation."""
18
+
19
+ source_file: str
20
+ line_number: int
21
+ turn_index: int
22
+ model: str
23
+ input_tokens: int
24
+ output_tokens: int
25
+ cache_read_tokens: int = 0
26
+ cache_write_tokens: int = 0
27
+ tools: tuple[str, ...] = field(default_factory=tuple)
28
+ is_error: bool = False
29
+
30
+ @property
31
+ def total_context(self) -> int:
32
+ return self.input_tokens + self.cache_read_tokens + self.cache_write_tokens
33
+
34
+ @property
35
+ def cache_hit_ratio(self) -> float:
36
+ denom = self.total_context
37
+ return (self.cache_read_tokens / denom) if denom > 0 else 0.0
38
+
39
+
40
+ def _as_int(value: Any) -> int:
41
+ if isinstance(value, bool):
42
+ return 0
43
+ if isinstance(value, (int, float)) and value > 0:
44
+ return int(value)
45
+ return 0
46
+
47
+
48
+ def _extract_tools(obj: dict[str, Any]) -> tuple[str, ...]:
49
+ names: list[str] = []
50
+ raw_tc = obj.get("tool_calls")
51
+ if isinstance(raw_tc, list):
52
+ for item in raw_tc:
53
+ if isinstance(item, dict):
54
+ name = item.get("name") or (item.get("function") or {}).get("name")
55
+ if isinstance(name, str) and name.strip():
56
+ names.append(name.strip())
57
+ msg = obj.get("message")
58
+ content = msg.get("content") if isinstance(msg, dict) else obj.get("content")
59
+ if isinstance(content, list):
60
+ for block in content:
61
+ if isinstance(block, dict) and block.get("type") in {"tool_use", "function_call"}:
62
+ name = block.get("name")
63
+ if isinstance(name, str) and name.strip():
64
+ names.append(name.strip())
65
+ return tuple(names)
66
+
67
+
68
+ def _extract_model(obj: dict[str, Any], default_model: str = "unknown") -> str:
69
+ for container in (obj, obj.get("message"), obj.get("response"), obj.get("step_update"), obj.get("init")):
70
+ if isinstance(container, dict):
71
+ m = container.get("model") or container.get("modelVersion")
72
+ if isinstance(m, str) and m.strip():
73
+ return m.strip()
74
+ return default_model
75
+
76
+
77
+ def _extract_usage_dict(obj: dict[str, Any]) -> dict[str, Any]:
78
+ for key in ("usage", "usageMetadata"):
79
+ val = obj.get(key)
80
+ if isinstance(val, dict):
81
+ return val
82
+ for nested_key in ("message", "response", "payload", "step_update"):
83
+ nested = obj.get(nested_key)
84
+ if isinstance(nested, dict):
85
+ for key in ("usage", "usageMetadata"):
86
+ val = nested.get(key)
87
+ if isinstance(val, dict):
88
+ return val
89
+ return obj
90
+
91
+
92
+ def _extract_tokens(usage: dict[str, Any]) -> tuple[int, int, int, int]:
93
+ """Return `(uncached_input, output, cache_read, cache_write)` across major vendor schemas."""
94
+ # Anthropic / Claude Code / Antigravity
95
+ in_tok = _as_int(usage.get("input_tokens"))
96
+ out_tok = _as_int(usage.get("output_tokens"))
97
+ cache_read = _as_int(usage.get("cache_read_input_tokens") or usage.get("cache_read_tokens"))
98
+ cache_write = _as_int(usage.get("cache_creation_input_tokens") or usage.get("cache_creation_tokens"))
99
+
100
+ # OpenAI / Codex / Cursor
101
+ if in_tok == 0 and out_tok == 0 and ("prompt_tokens" in usage or "completion_tokens" in usage):
102
+ prompt_tok = _as_int(usage.get("prompt_tokens"))
103
+ out_tok = _as_int(usage.get("completion_tokens"))
104
+ details = usage.get("prompt_tokens_details")
105
+ if isinstance(details, dict):
106
+ cache_read = _as_int(details.get("cached_tokens"))
107
+ in_tok = max(0, prompt_tok - cache_read)
108
+
109
+ # Gemini API
110
+ if in_tok == 0 and out_tok == 0 and ("promptTokenCount" in usage or "candidatesTokenCount" in usage):
111
+ prompt_tok = _as_int(usage.get("promptTokenCount"))
112
+ out_tok = _as_int(usage.get("candidatesTokenCount"))
113
+ cache_read = _as_int(usage.get("cachedContentTokenCount"))
114
+ in_tok = max(0, prompt_tok - cache_read)
115
+
116
+ return in_tok, out_tok, cache_read, cache_write
117
+
118
+
119
+ def parse_jsonl_file(path: Path, source_label: str | None = None) -> list[TurnRecord]:
120
+ """Parse one JSONL transcript file read-only into normalized TurnRecord entries."""
121
+ label = source_label if source_label is not None else path.name
122
+ turns: list[TurnRecord] = []
123
+ idx = 0
124
+ session_model = "unknown"
125
+ pending_tools: list[str] = []
126
+ fallback_result: tuple[int, dict[str, Any], tuple[int, int, int, int]] | None = None
127
+
128
+ with path.open("r", encoding="utf-8", errors="replace") as handle:
129
+ for line_no, raw in enumerate(handle, start=1):
130
+ stripped = raw.strip()
131
+ if not stripped or not stripped.startswith("{"):
132
+ continue
133
+ try:
134
+ obj = json.loads(stripped)
135
+ except (json.JSONDecodeError, TypeError, ValueError):
136
+ continue
137
+ if not isinstance(obj, dict):
138
+ continue
139
+
140
+ ev = str(obj.get("event") or "").lower()
141
+ if ev == "init":
142
+ session_model = _extract_model(obj, default_model=session_model)
143
+ continue
144
+
145
+ # Antigravity CLI `agy --output-format stream-json`: tool events arrive as step_update(step_type="tool")
146
+ su = obj.get("step_update")
147
+ if isinstance(su, dict) and su.get("step_type") == "tool":
148
+ if su.get("state") in {"DONE", "ERROR"}:
149
+ tname = su.get("tool_name") or (su.get("tool_info") or {}).get("name")
150
+ if isinstance(tname, str) and tname.strip():
151
+ if turns:
152
+ last = turns[-1]
153
+ turns[-1] = TurnRecord(
154
+ source_file=last.source_file,
155
+ line_number=last.line_number,
156
+ turn_index=last.turn_index,
157
+ model=last.model,
158
+ input_tokens=last.input_tokens,
159
+ output_tokens=last.output_tokens,
160
+ cache_read_tokens=last.cache_read_tokens,
161
+ cache_write_tokens=last.cache_write_tokens,
162
+ tools=(*last.tools, tname.strip()),
163
+ is_error=last.is_error or su.get("state") == "ERROR",
164
+ )
165
+ else:
166
+ pending_tools.append(tname.strip())
167
+ continue
168
+
169
+ # Avoid double-counting aggregate `result` summary when per-step usage already exists
170
+ if ev == "result" and isinstance(obj.get("result"), dict):
171
+ res_usage = obj["result"].get("usage")
172
+ if isinstance(res_usage, dict):
173
+ toks = _extract_tokens(res_usage)
174
+ if any(toks):
175
+ fallback_result = (line_no, obj["result"], toks)
176
+ continue
177
+
178
+ usage = _extract_usage_dict(obj)
179
+ in_tok, out_tok, cache_read, cache_write = _extract_tokens(usage)
180
+ if in_tok == 0 and out_tok == 0 and cache_read == 0 and cache_write == 0:
181
+ continue
182
+ idx += 1
183
+ status = str(obj.get("status") or (su.get("state") if isinstance(su, dict) else "") or "").upper()
184
+ is_err = bool(obj.get("error") or status == "ERROR")
185
+ tools = _extract_tools(obj)
186
+ if pending_tools:
187
+ tools = (*pending_tools, *tools)
188
+ pending_tools.clear()
189
+ turns.append(
190
+ TurnRecord(
191
+ source_file=label,
192
+ line_number=line_no,
193
+ turn_index=idx,
194
+ model=_extract_model(obj, default_model=session_model),
195
+ input_tokens=in_tok,
196
+ output_tokens=out_tok,
197
+ cache_read_tokens=cache_read,
198
+ cache_write_tokens=cache_write,
199
+ tools=tools,
200
+ is_error=is_err,
201
+ )
202
+ )
203
+
204
+ if not turns and fallback_result is not None:
205
+ line_no, res_obj, (in_tok, out_tok, cache_read, cache_write) = fallback_result
206
+ turns.append(
207
+ TurnRecord(
208
+ source_file=label,
209
+ line_number=line_no,
210
+ turn_index=1,
211
+ model=_extract_model(res_obj, default_model=session_model),
212
+ input_tokens=in_tok,
213
+ output_tokens=out_tok,
214
+ cache_read_tokens=cache_read,
215
+ cache_write_tokens=cache_write,
216
+ tools=tuple(pending_tools),
217
+ is_error=str(res_obj.get("status") or "").upper() == "ERROR",
218
+ )
219
+ )
220
+ return turns
221
+
222
+
223
+ def collect_jsonl_entries(raw_paths: Iterable[str]) -> list[tuple[Path, str]]:
224
+ """Resolve file/directory inputs into sorted deduplicated `(path, source_label)` pairs.
225
+
226
+ Directory scans key each file by its POSIX relative path from the scan root
227
+ (e.g. `run1/transcript.jsonl`), falling back to `path.name` only for single-file
228
+ inputs. Any remaining cross-root label collisions are disambiguated automatically.
229
+ """
230
+ entries: dict[Path, str] = {}
231
+ for raw in raw_paths:
232
+ target = Path(raw).expanduser().absolute()
233
+ if not target.exists():
234
+ raise FileNotFoundError(f"path does not exist: {target}")
235
+ if target.is_file():
236
+ entries.setdefault(target, target.name)
237
+ continue
238
+ for cur_root, dirs, files in os.walk(target):
239
+ dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
240
+ for fname in sorted(files):
241
+ if fname.lower().endswith(".jsonl"):
242
+ fpath = Path(cur_root) / fname
243
+ rel = fpath.relative_to(target).as_posix()
244
+ entries.setdefault(fpath, rel)
245
+
246
+ sorted_items = sorted(entries.items(), key=lambda item: item[0])
247
+ label_counts: dict[str, int] = {}
248
+ for _p, lbl in sorted_items:
249
+ label_counts[lbl] = label_counts.get(lbl, 0) + 1
250
+
251
+ if any(count > 1 for count in label_counts.values()):
252
+ colliding_paths = [p for p, lbl in sorted_items if label_counts[lbl] > 1]
253
+ try:
254
+ common = Path(os.path.commonpath([str(p.parent) for p in colliding_paths]))
255
+ except ValueError:
256
+ common = None
257
+ disambiguated: list[tuple[Path, str]] = []
258
+ for fpath, lbl in sorted_items:
259
+ final_lbl = lbl
260
+ if label_counts[lbl] > 1:
261
+ if common is not None:
262
+ try:
263
+ final_lbl = fpath.relative_to(common).as_posix()
264
+ except ValueError:
265
+ final_lbl = fpath.as_posix()
266
+ else:
267
+ final_lbl = fpath.as_posix()
268
+ disambiguated.append((fpath, final_lbl))
269
+ return disambiguated
270
+
271
+ return sorted_items
272
+
273
+
274
+ def collect_jsonl_files(raw_paths: Iterable[str]) -> list[Path]:
275
+ """Resolve file and directory paths into a sorted deduplicated list of `.jsonl` files."""
276
+ return [fpath for fpath, _label in collect_jsonl_entries(raw_paths)]
@@ -0,0 +1,188 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-token-forensics
3
+ Version: 0.1.0
4
+ Summary: Read-only JSONL token & prompt-cache burn forensics for Claude Code, Codex CLI, Cursor, Gemini, and Antigravity.
5
+ Author: BlackBadHope
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://integrity.subnet.zp.ua
8
+ Project-URL: Repository, https://github.com/BlackBadHope/agent-token-forensics
9
+ Project-URL: Issues, https://github.com/BlackBadHope/agent-token-forensics/issues
10
+ Keywords: ai-agents,llm-ops,claude-code,codex,cursor,tokens,prompt-cache,cost-optimization
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Software Development :: Quality Assurance
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Dynamic: license-file
28
+
29
+ # agent-token-forensics
30
+
31
+ [![CI](https://github.com/BlackBadHope/agent-token-forensics/actions/workflows/ci.yml/badge.svg)](https://github.com/BlackBadHope/agent-token-forensics/actions/workflows/ci.yml)
32
+
33
+ **Read-only JSONL token, prompt-cache, compaction-point, and retry-loop forensics for autonomous AI coding agents** (Claude Code, Codex CLI, Cursor, Gemini CLI, Antigravity).
34
+
35
+ Long agent sessions silently burn 30–55% of their quota on uncompacted context tails, broken prompt caches, and identical retry loops. `agent-token-forensics` inspects your local JSONL transcripts **strictly read-only** with **zero external dependencies** (pure Python 3.10+ stdlib, zero network calls) and pinpoints the exact turns costing you money.
36
+
37
+ - **Multi-vendor JSONL schema support:** Claude Code / Anthropic (`usage.input_tokens`, `cache_read_input_tokens`), OpenAI / Codex / Cursor (`prompt_tokens`, `prompt_tokens_details.cached_tokens`), Gemini (`usageMetadata`), and Antigravity flat transcripts.
38
+ - **Compaction inflection finder:** identifies the exact turn where context crosses `--compact-threshold` (default `80 000` tokens) and estimates realistic token & USD savings from compacting there.
39
+ - **Prompt-cache bust detector:** catches turns where a warm cache (`>=70%` hit ratio) suddenly collapses (`<30%`).
40
+ - **Retry-loop & tool-bloat forensics:** flags `>=3` consecutive identical tool invocations and ranks tools by attributed token burn.
41
+
42
+ ---
43
+
44
+ ## 60-Second Install & Zero-Install Run
45
+
46
+ > **PyPI status:** The `agent-token-forensics` package name is uncontested on PyPI for the upcoming PyPI release (`pip install agent-token-forensics` / `pipx install agent-token-forensics` once published). Until then, use zero-install or install from source below.
47
+
48
+ ### Linux / macOS (`bash`)
49
+
50
+ ```bash
51
+ # Option 1: Zero-Install Direct Run (pure Python 3.10+ stdlib)
52
+ git clone https://github.com/BlackBadHope/agent-token-forensics
53
+ cd agent-token-forensics
54
+ python3 agent_token_forensics_cli.py analyze ./transcripts --markdown
55
+ python3 agent_token_forensics_cli.py analyze ./session.jsonl --json
56
+
57
+ # Option 2: Isolated CLI Install (uvx / pipx / .venv — PEP 668 safe)
58
+ uvx --from . agent-token-forensics analyze ./transcripts --markdown
59
+ pipx install . && agent-token-forensics analyze ./transcripts --markdown
60
+
61
+ python3 -m venv .venv
62
+ .venv/bin/python -m pip install --no-deps .
63
+ .venv/bin/agent-token-forensics analyze ./transcripts --markdown
64
+ ```
65
+
66
+ ### Windows (`pwsh 7`)
67
+
68
+ ```powershell
69
+ # Option 1: Zero-Install Direct Run (pure Python 3.10+ stdlib)
70
+ git clone https://github.com/BlackBadHope/agent-token-forensics
71
+ Set-Location .\agent-token-forensics
72
+ python agent_token_forensics_cli.py analyze .\transcripts --markdown
73
+ python agent_token_forensics_cli.py analyze .\session.jsonl --json
74
+
75
+ # Option 2: Isolated virtual environment (.venv) from source
76
+ python -m venv .venv
77
+ .\.venv\Scripts\python.exe -m pip install --no-deps .
78
+ .\.venv\Scripts\agent-token-forensics.exe analyze .\transcripts --markdown
79
+ ```
80
+
81
+ ---
82
+
83
+ ## MCP Server (stdio)
84
+
85
+ `agent-token-forensics` ships a zero-dependency, **strictly read-only** MCP JSON-RPC 2.0 server over `stdio` (pure Python 3.10+ stdlib, zero writes, zero telemetry, zero network calls).
86
+
87
+ **Exposed Read-Only Tools:**
88
+ - `analyze_transcripts` — analyzes a JSONL transcript file or directory (`path`, optional `compact_threshold`, `post_compact_target`, `output_format`: `"json"` | `"markdown"`) and returns `cache_bust_events`, `compaction_inflection_points`, `retry_loops`, `top_tools_by_tokens`, and cost/savings summary.
89
+ - `forensics_about` — returns version, supported transcript schemas (Claude Code/Anthropic, OpenAI/Codex/Cursor, Gemini `usageMetadata`, Antigravity), and zero-telemetry / read-only guarantees.
90
+
91
+ **Run directly from a cloned repo or source install:**
92
+
93
+ ```bash
94
+ python -m agent_token_forensics.mcp_server
95
+ # or via the zero-install shim / installed CLI:
96
+ python agent_token_forensics_cli.py mcp-serve
97
+ agent-token-forensics mcp-serve
98
+ ```
99
+
100
+ **Claude Code / Cursor / Antigravity MCP config (`mcpServers`):**
101
+
102
+ ```json
103
+ {
104
+ "mcpServers": {
105
+ "agent-token-forensics": {
106
+ "command": "python",
107
+ "args": ["/path/to/agent-token-forensics/agent_token_forensics_cli.py", "mcp-serve"]
108
+ }
109
+ }
110
+ }
111
+ ```
112
+
113
+ Or if installed from source into your environment (or via `uvx --from git+https://github.com/BlackBadHope/agent-token-forensics`):
114
+
115
+ ```json
116
+ {
117
+ "mcpServers": {
118
+ "agent-token-forensics": {
119
+ "command": "python",
120
+ "args": ["-m", "agent_token_forensics.mcp_server"]
121
+ }
122
+ }
123
+ }
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Troubleshooting & Clean Uninstall
129
+
130
+ ### 1. Ubuntu / Debian 24.04: `error: externally-managed-environment` (PEP 668)
131
+
132
+ Modern Debian/Ubuntu blocks global `pip install` under PEP 668. Use either clean option (no `--break-system-packages` needed):
133
+
134
+ ```bash
135
+ # Option A: Zero-install direct run (pure Python 3.10+ stdlib)
136
+ python3 agent_token_forensics_cli.py analyze ./session.jsonl --markdown
137
+
138
+ # Option B: Isolated virtual environment (zero external deps)
139
+ python3 -m venv .venv
140
+ .venv/bin/python -m pip install --no-deps .
141
+ .venv/bin/agent-token-forensics analyze ./transcripts --markdown
142
+ ```
143
+
144
+ ### 2. Empty Directories, Zero-Turn Files, and Corrupt JSONL Lines
145
+
146
+ `agent-token-forensics` is strictly read-only and designed to survive messy real-world logs:
147
+
148
+ - **Empty directory or no `.jsonl` files:** exits `0` with a clean zero-turn summary (`files_scanned: 0`, `turns: 0`) rather than crashing.
149
+ - **Truncated, malformed, or non-UTF-8 JSONL lines:** invalid lines and non-usage metadata events are skipped safely (`errors="replace"`), while all valid turns in the same file are still analyzed.
150
+ - **Non-existent path:** fails explicitly with exit `2` and an error message on `stderr`.
151
+ - **No compaction recommendations shown:** your sessions stayed under `--compact-threshold` (default `80000` tokens); lower it (e.g. `--compact-threshold 40000`) for smaller context windows.
152
+
153
+ ### 3. Clean Uninstall / Reset-to-Zero
154
+
155
+ `agent-token-forensics` creates **zero** hidden state directories, caches, or background daemons. To uninstall and reset to zero:
156
+
157
+ ```bash
158
+ # Linux / macOS
159
+ python3 -m pip uninstall -y agent-token-forensics 2>/dev/null || true
160
+ rm -rf ./agent-token-forensics # or remove your .venv directory
161
+ ```
162
+
163
+ ```powershell
164
+ # Windows (PowerShell 7)
165
+ python -m pip uninstall -y agent-token-forensics
166
+ Remove-Item -Recurse -Force ".\agent-token-forensics" -ErrorAction SilentlyContinue
167
+ ```
168
+
169
+ ---
170
+
171
+ ## Full Production Suite, Bundles & Cloud Control Plane
172
+
173
+ - **Cloud Control Plane (Hybrid SaaS):** [integrity.subnet.zp.ua](https://integrity.subnet.zp.ua) — SHA-256 Cloud Witness notarization, central multi-host Killswitch API, and team license management.
174
+ - **1-Click MCP Skills & Paid Packs (Agensi Storefront):** [agensi.io/r/BLACKHOPE](https://www.agensi.io/r/BLACKHOPE)
175
+ - **Production Agent Reliability Suite ($35, Save 19%):** [Evidence-Budget Test & Monitor Gate + Zero-LLM Swarm Heartbeat & Orthogonal Consensus](https://www.agensi.io/bundles/production-agent-reliability-suite)
176
+ - **Master All-Access Agent Governance Bundle ($79, Save 48% off $151):** [All 4 Paid Governance Packs (Evidence Gate + Swarm Consensus + Uroboros Ops-Route Audit + Cross-Host pwsh 7 / Linux Safety Suite)](https://www.agensi.io/bundles/master-all-access-agent-governance-bundle)
177
+ - **Free OS Process-Tree Killswitch:** [BlackBadHope/agent-killswitch](https://github.com/BlackBadHope/agent-killswitch)
178
+
179
+ ## Development & Verification
180
+
181
+ ```bash
182
+ ruff check agent_token_forensics agent_token_forensics_cli.py tests agensi-skill
183
+ python -m unittest discover -s tests -p "test_*.py" -v
184
+ ```
185
+
186
+ ## License
187
+
188
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,12 @@
1
+ agent_token_forensics/__init__.py,sha256=zM-qNLAoeBXrRCGbsWCWrgOx5nIWOuQwPa9L_HIBkMw,652
2
+ agent_token_forensics/__main__.py,sha256=apvMeuuGhpv7OSRQfss_Wn2tuX-nn86w0nmh7SX_kHE,224
3
+ agent_token_forensics/analyzer.py,sha256=lcnrjNGW1Sn19Y1Xk8LWXlYFpECfC0oYWNOq_-XdT38,10780
4
+ agent_token_forensics/cli.py,sha256=N0NWQ6z-hV_cXG1GLK5OoKca9OHjNxrHzrvSWvH04tg,2026
5
+ agent_token_forensics/mcp_server.py,sha256=d1XHT6IuCgcxQH6e-FQXQZY74FaWlwISPCBw-4OIr7E,11932
6
+ agent_token_forensics/parser.py,sha256=W3MuliRK5V_1SJc0gOSfX7rCBktj7JzWz_o9j3DW9V8,11554
7
+ agent_token_forensics-0.1.0.dist-info/licenses/LICENSE,sha256=I1eDcuopCx3pfl3E4i2H8Rqr-VBeNisZHsmasWKJEUY,1069
8
+ agent_token_forensics-0.1.0.dist-info/METADATA,sha256=vNpWB3pRRRtULQGuochk3RzMYjvDwoW_1yGVE_cT8Lo,9098
9
+ agent_token_forensics-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ agent_token_forensics-0.1.0.dist-info/entry_points.txt,sha256=u2Ab2m28ZuctN0JRipU8_6SCycCw2kuQ8avDesInS6A,73
11
+ agent_token_forensics-0.1.0.dist-info/top_level.txt,sha256=nMtSRJYpxFhsljIWm-ra1K8PINBW3iNUUg_23aFZJ00,22
12
+ agent_token_forensics-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ agent-token-forensics = agent_token_forensics.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BlackBadHope
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ agent_token_forensics