agent-token-forensics 0.1.0__tar.gz
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.
- agent_token_forensics-0.1.0/LICENSE +21 -0
- agent_token_forensics-0.1.0/PKG-INFO +188 -0
- agent_token_forensics-0.1.0/README.md +160 -0
- agent_token_forensics-0.1.0/agent_token_forensics/__init__.py +28 -0
- agent_token_forensics-0.1.0/agent_token_forensics/__main__.py +10 -0
- agent_token_forensics-0.1.0/agent_token_forensics/analyzer.py +269 -0
- agent_token_forensics-0.1.0/agent_token_forensics/cli.py +55 -0
- agent_token_forensics-0.1.0/agent_token_forensics/mcp_server.py +325 -0
- agent_token_forensics-0.1.0/agent_token_forensics/parser.py +276 -0
- agent_token_forensics-0.1.0/agent_token_forensics.egg-info/PKG-INFO +188 -0
- agent_token_forensics-0.1.0/agent_token_forensics.egg-info/SOURCES.txt +16 -0
- agent_token_forensics-0.1.0/agent_token_forensics.egg-info/dependency_links.txt +1 -0
- agent_token_forensics-0.1.0/agent_token_forensics.egg-info/entry_points.txt +2 -0
- agent_token_forensics-0.1.0/agent_token_forensics.egg-info/top_level.txt +1 -0
- agent_token_forensics-0.1.0/pyproject.toml +51 -0
- agent_token_forensics-0.1.0/setup.cfg +4 -0
- agent_token_forensics-0.1.0/tests/test_mcp_server.py +354 -0
- agent_token_forensics-0.1.0/tests/test_token_forensics.py +533 -0
|
@@ -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,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
|
+
[](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,160 @@
|
|
|
1
|
+
# agent-token-forensics
|
|
2
|
+
|
|
3
|
+
[](https://github.com/BlackBadHope/agent-token-forensics/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
**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).
|
|
6
|
+
|
|
7
|
+
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.
|
|
8
|
+
|
|
9
|
+
- **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.
|
|
10
|
+
- **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.
|
|
11
|
+
- **Prompt-cache bust detector:** catches turns where a warm cache (`>=70%` hit ratio) suddenly collapses (`<30%`).
|
|
12
|
+
- **Retry-loop & tool-bloat forensics:** flags `>=3` consecutive identical tool invocations and ranks tools by attributed token burn.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## 60-Second Install & Zero-Install Run
|
|
17
|
+
|
|
18
|
+
> **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.
|
|
19
|
+
|
|
20
|
+
### Linux / macOS (`bash`)
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
# Option 1: Zero-Install Direct Run (pure Python 3.10+ stdlib)
|
|
24
|
+
git clone https://github.com/BlackBadHope/agent-token-forensics
|
|
25
|
+
cd agent-token-forensics
|
|
26
|
+
python3 agent_token_forensics_cli.py analyze ./transcripts --markdown
|
|
27
|
+
python3 agent_token_forensics_cli.py analyze ./session.jsonl --json
|
|
28
|
+
|
|
29
|
+
# Option 2: Isolated CLI Install (uvx / pipx / .venv — PEP 668 safe)
|
|
30
|
+
uvx --from . agent-token-forensics analyze ./transcripts --markdown
|
|
31
|
+
pipx install . && agent-token-forensics analyze ./transcripts --markdown
|
|
32
|
+
|
|
33
|
+
python3 -m venv .venv
|
|
34
|
+
.venv/bin/python -m pip install --no-deps .
|
|
35
|
+
.venv/bin/agent-token-forensics analyze ./transcripts --markdown
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Windows (`pwsh 7`)
|
|
39
|
+
|
|
40
|
+
```powershell
|
|
41
|
+
# Option 1: Zero-Install Direct Run (pure Python 3.10+ stdlib)
|
|
42
|
+
git clone https://github.com/BlackBadHope/agent-token-forensics
|
|
43
|
+
Set-Location .\agent-token-forensics
|
|
44
|
+
python agent_token_forensics_cli.py analyze .\transcripts --markdown
|
|
45
|
+
python agent_token_forensics_cli.py analyze .\session.jsonl --json
|
|
46
|
+
|
|
47
|
+
# Option 2: Isolated virtual environment (.venv) from source
|
|
48
|
+
python -m venv .venv
|
|
49
|
+
.\.venv\Scripts\python.exe -m pip install --no-deps .
|
|
50
|
+
.\.venv\Scripts\agent-token-forensics.exe analyze .\transcripts --markdown
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## MCP Server (stdio)
|
|
56
|
+
|
|
57
|
+
`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).
|
|
58
|
+
|
|
59
|
+
**Exposed Read-Only Tools:**
|
|
60
|
+
- `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.
|
|
61
|
+
- `forensics_about` — returns version, supported transcript schemas (Claude Code/Anthropic, OpenAI/Codex/Cursor, Gemini `usageMetadata`, Antigravity), and zero-telemetry / read-only guarantees.
|
|
62
|
+
|
|
63
|
+
**Run directly from a cloned repo or source install:**
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
python -m agent_token_forensics.mcp_server
|
|
67
|
+
# or via the zero-install shim / installed CLI:
|
|
68
|
+
python agent_token_forensics_cli.py mcp-serve
|
|
69
|
+
agent-token-forensics mcp-serve
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**Claude Code / Cursor / Antigravity MCP config (`mcpServers`):**
|
|
73
|
+
|
|
74
|
+
```json
|
|
75
|
+
{
|
|
76
|
+
"mcpServers": {
|
|
77
|
+
"agent-token-forensics": {
|
|
78
|
+
"command": "python",
|
|
79
|
+
"args": ["/path/to/agent-token-forensics/agent_token_forensics_cli.py", "mcp-serve"]
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Or if installed from source into your environment (or via `uvx --from git+https://github.com/BlackBadHope/agent-token-forensics`):
|
|
86
|
+
|
|
87
|
+
```json
|
|
88
|
+
{
|
|
89
|
+
"mcpServers": {
|
|
90
|
+
"agent-token-forensics": {
|
|
91
|
+
"command": "python",
|
|
92
|
+
"args": ["-m", "agent_token_forensics.mcp_server"]
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## Troubleshooting & Clean Uninstall
|
|
101
|
+
|
|
102
|
+
### 1. Ubuntu / Debian 24.04: `error: externally-managed-environment` (PEP 668)
|
|
103
|
+
|
|
104
|
+
Modern Debian/Ubuntu blocks global `pip install` under PEP 668. Use either clean option (no `--break-system-packages` needed):
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
# Option A: Zero-install direct run (pure Python 3.10+ stdlib)
|
|
108
|
+
python3 agent_token_forensics_cli.py analyze ./session.jsonl --markdown
|
|
109
|
+
|
|
110
|
+
# Option B: Isolated virtual environment (zero external deps)
|
|
111
|
+
python3 -m venv .venv
|
|
112
|
+
.venv/bin/python -m pip install --no-deps .
|
|
113
|
+
.venv/bin/agent-token-forensics analyze ./transcripts --markdown
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### 2. Empty Directories, Zero-Turn Files, and Corrupt JSONL Lines
|
|
117
|
+
|
|
118
|
+
`agent-token-forensics` is strictly read-only and designed to survive messy real-world logs:
|
|
119
|
+
|
|
120
|
+
- **Empty directory or no `.jsonl` files:** exits `0` with a clean zero-turn summary (`files_scanned: 0`, `turns: 0`) rather than crashing.
|
|
121
|
+
- **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.
|
|
122
|
+
- **Non-existent path:** fails explicitly with exit `2` and an error message on `stderr`.
|
|
123
|
+
- **No compaction recommendations shown:** your sessions stayed under `--compact-threshold` (default `80000` tokens); lower it (e.g. `--compact-threshold 40000`) for smaller context windows.
|
|
124
|
+
|
|
125
|
+
### 3. Clean Uninstall / Reset-to-Zero
|
|
126
|
+
|
|
127
|
+
`agent-token-forensics` creates **zero** hidden state directories, caches, or background daemons. To uninstall and reset to zero:
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
# Linux / macOS
|
|
131
|
+
python3 -m pip uninstall -y agent-token-forensics 2>/dev/null || true
|
|
132
|
+
rm -rf ./agent-token-forensics # or remove your .venv directory
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
```powershell
|
|
136
|
+
# Windows (PowerShell 7)
|
|
137
|
+
python -m pip uninstall -y agent-token-forensics
|
|
138
|
+
Remove-Item -Recurse -Force ".\agent-token-forensics" -ErrorAction SilentlyContinue
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
## Full Production Suite, Bundles & Cloud Control Plane
|
|
144
|
+
|
|
145
|
+
- **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.
|
|
146
|
+
- **1-Click MCP Skills & Paid Packs (Agensi Storefront):** [agensi.io/r/BLACKHOPE](https://www.agensi.io/r/BLACKHOPE)
|
|
147
|
+
- **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)
|
|
148
|
+
- **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)
|
|
149
|
+
- **Free OS Process-Tree Killswitch:** [BlackBadHope/agent-killswitch](https://github.com/BlackBadHope/agent-killswitch)
|
|
150
|
+
|
|
151
|
+
## Development & Verification
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
ruff check agent_token_forensics agent_token_forensics_cli.py tests agensi-skill
|
|
155
|
+
python -m unittest discover -s tests -p "test_*.py" -v
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -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,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)
|