agent-efficiency 1.4.2__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.
- agent_efficiency/__init__.py +15 -0
- agent_efficiency/_bundle/mcp/server.py +519 -0
- agent_efficiency/_bundle/rules/AGENT_RULES.md +9 -0
- agent_efficiency/_bundle/scripts/ae_cli.py +327 -0
- agent_efficiency/_bundle/scripts/ae_init.py +267 -0
- agent_efficiency/_bundle/scripts/ae_manage.py +578 -0
- agent_efficiency/_bundle/scripts/install.py +308 -0
- agent_efficiency/_bundle/scripts/pretool_hook.py +350 -0
- agent_efficiency/_bundle/scripts/render_demo_svg.py +180 -0
- agent_efficiency/_bundle/scripts/setup_hooks.py +330 -0
- agent_efficiency/_bundle/scripts/sync_shared.py +85 -0
- agent_efficiency/_bundle/scripts/validate_skills.py +150 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/SKILL.md +80 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/config/models.json +237 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/examples/workflow.md +77 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/routing-and-escalation.md +63 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/state-and-handoff.md +84 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/agent_state.py +266 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/context_doctor.py +780 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/llm_adapter.py +306 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/route_task.py +496 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_ops.py +580 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_render.py +428 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_store.py +440 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/transcript_audit.py +854 -0
- agent_efficiency/_bundle/skills/local-context-index/SKILL.md +71 -0
- agent_efficiency/_bundle/skills/local-context-index/references/cli-reference.md +112 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/compact_run.py +395 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/context_index.py +341 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_db.py +393 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_ignore.py +184 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_indexer.py +330 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_lsp.py +213 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_parsers.py +769 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_search.py +498 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_slice.py +610 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_trace.py +553 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_workspace.py +219 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/SKILL.md +52 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/references/provider-caching.md +52 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/cache_payload.py +278 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/prompt_cache.py +488 -0
- agent_efficiency/cli.py +23 -0
- agent_efficiency/mcp_entry.py +25 -0
- agent_efficiency-1.4.2.dist-info/METADATA +267 -0
- agent_efficiency-1.4.2.dist-info/RECORD +64 -0
- agent_efficiency-1.4.2.dist-info/WHEEL +4 -0
- agent_efficiency-1.4.2.dist-info/entry_points.txt +4 -0
- agent_efficiency-1.4.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""Persistent local savings counter & statusline formatter (zero-dependency, lock-safe)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import tempfile
|
|
7
|
+
import time
|
|
8
|
+
from collections import defaultdict
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
11
|
+
|
|
12
|
+
from _ae_core.io_lock import file_lock
|
|
13
|
+
|
|
14
|
+
DEFAULT_RATE_PER_1M_USD = 3.00 # Balanced input token reference rate (e.g., Sonnet-class)
|
|
15
|
+
MAX_HISTORY_LINES = 2500
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def default_savings_path() -> Path:
|
|
19
|
+
override = os.getenv("AGENT_EFFICIENCY_SAVINGS_FILE", "").strip()
|
|
20
|
+
if override:
|
|
21
|
+
return Path(override).expanduser()
|
|
22
|
+
return Path.home() / ".agent-efficiency" / "savings.jsonl"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _is_temp_repo(repo: Optional[Path]) -> bool:
|
|
26
|
+
if repo is None:
|
|
27
|
+
return False
|
|
28
|
+
try:
|
|
29
|
+
rp = str(repo.resolve()).lower()
|
|
30
|
+
td = str(Path(tempfile.gettempdir()).resolve()).lower()
|
|
31
|
+
if rp.startswith(td):
|
|
32
|
+
return True
|
|
33
|
+
for prefix in ("/tmp/", "/private/tmp/", "/var/folders/", "/private/var/folders/"):
|
|
34
|
+
if rp.startswith(prefix):
|
|
35
|
+
return True
|
|
36
|
+
except Exception:
|
|
37
|
+
return False
|
|
38
|
+
return False
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def record_saving(
|
|
42
|
+
cmd: str,
|
|
43
|
+
raw_tokens: int,
|
|
44
|
+
compact_tokens: int,
|
|
45
|
+
*,
|
|
46
|
+
repo: Optional[Path] = None,
|
|
47
|
+
savings_path: Optional[Path] = None,
|
|
48
|
+
) -> Optional[Dict[str, Any]]:
|
|
49
|
+
"""Append one compact savings event to local JSONL telemetry (strictly non-fatal)."""
|
|
50
|
+
if os.getenv("AGENT_EFFICIENCY_DISABLE_SAVINGS", "").strip() in ("1", "true", "yes"):
|
|
51
|
+
return None
|
|
52
|
+
raw_t = max(0, int(raw_tokens))
|
|
53
|
+
out_t = max(0, int(compact_tokens))
|
|
54
|
+
saved_t = max(0, raw_t - out_t)
|
|
55
|
+
if saved_t <= 0 and raw_t <= 0:
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
has_explicit_target = savings_path is not None or bool(os.getenv("AGENT_EFFICIENCY_SAVINGS_FILE", "").strip())
|
|
59
|
+
if not has_explicit_target and _is_temp_repo(repo):
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
target = (savings_path or default_savings_path()).expanduser()
|
|
63
|
+
rec = {
|
|
64
|
+
"ts": int(time.time()),
|
|
65
|
+
"cmd": str(cmd)[:32],
|
|
66
|
+
"repo": repo.resolve().name[:48] if repo is not None else "",
|
|
67
|
+
"raw_tok": raw_t,
|
|
68
|
+
"out_tok": out_t,
|
|
69
|
+
"saved_tok": saved_t,
|
|
70
|
+
}
|
|
71
|
+
try:
|
|
72
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
lock_file = target.parent / ".savings.lock"
|
|
74
|
+
with file_lock(lock_file, timeout_s=1.5):
|
|
75
|
+
with target.open("a", encoding="utf-8") as fh:
|
|
76
|
+
fh.write(json.dumps(rec, separators=(",", ":")) + "\n")
|
|
77
|
+
# Trim periodically if file grows large
|
|
78
|
+
try:
|
|
79
|
+
if target.stat().st_size > 260_000:
|
|
80
|
+
lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
81
|
+
if len(lines) > MAX_HISTORY_LINES:
|
|
82
|
+
kept = lines[-MAX_HISTORY_LINES:]
|
|
83
|
+
target.write_text("\n".join(kept) + "\n", encoding="utf-8")
|
|
84
|
+
except OSError:
|
|
85
|
+
pass
|
|
86
|
+
return rec
|
|
87
|
+
except Exception:
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def summarize_savings(
|
|
92
|
+
*,
|
|
93
|
+
days: Optional[int] = 7,
|
|
94
|
+
rate_per_1m_usd: float = DEFAULT_RATE_PER_1M_USD,
|
|
95
|
+
savings_path: Optional[Path] = None,
|
|
96
|
+
repo_filter: Optional[str] = None,
|
|
97
|
+
) -> Dict[str, Any]:
|
|
98
|
+
"""Aggregate recorded token & USD savings over the requested time window (`days=None` for all-time)."""
|
|
99
|
+
target = (savings_path or default_savings_path()).expanduser()
|
|
100
|
+
now = int(time.time())
|
|
101
|
+
cutoff = (now - int(days) * 86400) if (days is not None and days > 0) else 0
|
|
102
|
+
|
|
103
|
+
events = 0
|
|
104
|
+
total_raw = 0
|
|
105
|
+
total_out = 0
|
|
106
|
+
total_saved = 0
|
|
107
|
+
by_cmd: Dict[str, Dict[str, int]] = defaultdict(lambda: {"calls": 0, "raw_tok": 0, "out_tok": 0, "saved_tok": 0})
|
|
108
|
+
repos: Dict[str, int] = defaultdict(int)
|
|
109
|
+
|
|
110
|
+
if target.is_file():
|
|
111
|
+
try:
|
|
112
|
+
for line in target.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
113
|
+
line = line.strip()
|
|
114
|
+
if not line:
|
|
115
|
+
continue
|
|
116
|
+
try:
|
|
117
|
+
rec = json.loads(line)
|
|
118
|
+
except Exception:
|
|
119
|
+
continue
|
|
120
|
+
if not isinstance(rec, dict):
|
|
121
|
+
continue
|
|
122
|
+
ts = int(rec.get("ts", 0))
|
|
123
|
+
if cutoff and ts < cutoff:
|
|
124
|
+
continue
|
|
125
|
+
rname = str(rec.get("repo", ""))
|
|
126
|
+
if repo_filter and rname != repo_filter:
|
|
127
|
+
continue
|
|
128
|
+
raw_t = max(0, int(rec.get("raw_tok", 0)))
|
|
129
|
+
out_t = max(0, int(rec.get("out_tok", 0)))
|
|
130
|
+
saved_t = max(0, int(rec.get("saved_tok", max(0, raw_t - out_t))))
|
|
131
|
+
cname = str(rec.get("cmd", "other"))
|
|
132
|
+
events += 1
|
|
133
|
+
total_raw += raw_t
|
|
134
|
+
total_out += out_t
|
|
135
|
+
total_saved += saved_t
|
|
136
|
+
c = by_cmd[cname]
|
|
137
|
+
c["calls"] += 1
|
|
138
|
+
c["raw_tok"] += raw_t
|
|
139
|
+
c["out_tok"] += out_t
|
|
140
|
+
c["saved_tok"] += saved_t
|
|
141
|
+
if rname:
|
|
142
|
+
repos[rname] += saved_t
|
|
143
|
+
except OSError:
|
|
144
|
+
pass
|
|
145
|
+
|
|
146
|
+
pct = round((total_saved / max(1, total_raw)) * 100.0, 1) if total_raw > 0 else 0.0
|
|
147
|
+
est_usd = round((total_saved / 1_000_000.0) * float(rate_per_1m_usd), 4)
|
|
148
|
+
breakdown = [
|
|
149
|
+
{
|
|
150
|
+
"cmd": k,
|
|
151
|
+
"calls": v["calls"],
|
|
152
|
+
"raw_tokens": v["raw_tok"],
|
|
153
|
+
"output_tokens": v["out_tok"],
|
|
154
|
+
"saved_tokens": v["saved_tok"],
|
|
155
|
+
"savings_pct": round((v["saved_tok"] / max(1, v["raw_tok"])) * 100.0, 1) if v["raw_tok"] > 0 else 0.0,
|
|
156
|
+
}
|
|
157
|
+
for k, v in sorted(by_cmd.items(), key=lambda kv: (-kv[1]["saved_tok"], kv[0]))
|
|
158
|
+
]
|
|
159
|
+
top_repos = [{"repo": r, "saved_tokens": tok} for r, tok in sorted(repos.items(), key=lambda kv: (-kv[1], kv[0]))[:5]]
|
|
160
|
+
window_label = f"{days}d" if (days is not None and days > 0) else "all-time"
|
|
161
|
+
return {
|
|
162
|
+
"window": window_label,
|
|
163
|
+
"days": days,
|
|
164
|
+
"events": events,
|
|
165
|
+
"raw_tokens_est": total_raw,
|
|
166
|
+
"output_tokens_est": total_out,
|
|
167
|
+
"saved_tokens_est": total_saved,
|
|
168
|
+
"savings_pct": pct,
|
|
169
|
+
"est_usd_saved": est_usd,
|
|
170
|
+
"rate_per_1m_usd": rate_per_1m_usd,
|
|
171
|
+
"by_command": breakdown,
|
|
172
|
+
"top_repos": top_repos,
|
|
173
|
+
"savings_file": str(target),
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _fmt_tok(n: int) -> str:
|
|
178
|
+
if n >= 1_000_000:
|
|
179
|
+
return f"{n / 1_000_000:.2f}M"
|
|
180
|
+
if n >= 1_000:
|
|
181
|
+
return f"{n / 1_000:.1f}k"
|
|
182
|
+
return str(n)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _bar(fraction: float, width: int = 18) -> str:
|
|
186
|
+
frac = max(0.0, min(1.0, fraction))
|
|
187
|
+
filled = int(round(frac * width))
|
|
188
|
+
return "█" * filled + "░" * (width - filled)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def format_statusline(summary: Dict[str, Any]) -> str:
|
|
192
|
+
"""Single-line status string for Claude Code statusLine or shell prompt."""
|
|
193
|
+
saved = int(summary.get("saved_tokens_est", 0))
|
|
194
|
+
if saved <= 0:
|
|
195
|
+
return f"ae: 0 tok saved ({summary.get('window', '7d')})"
|
|
196
|
+
usd = float(summary.get("est_usd_saved", 0.0))
|
|
197
|
+
pct = float(summary.get("savings_pct", 0.0))
|
|
198
|
+
win = summary.get("window", "7d")
|
|
199
|
+
usd_str = f"${usd:.2f}" if usd >= 0.01 else f"${usd:.4f}"
|
|
200
|
+
return f"ae: -{_fmt_tok(saved)} tok (-{pct:.0f}%, ~{usd_str} saved / {win})"
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _box_row(text: str, width: int = 60) -> str:
|
|
204
|
+
clipped = text if len(text) <= width else (text[: max(1, width - 1)] + "…")
|
|
205
|
+
return f"│{clipped:<{width}}│"
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def format_savings_card(summary: Dict[str, Any]) -> str:
|
|
209
|
+
"""Render a crisp, shareable terminal receipt of AgentEfficiency savings."""
|
|
210
|
+
win = summary["window"]
|
|
211
|
+
saved = int(summary["saved_tokens_est"])
|
|
212
|
+
raw = int(summary["raw_tokens_est"])
|
|
213
|
+
out = int(summary["output_tokens_est"])
|
|
214
|
+
pct = float(summary["savings_pct"])
|
|
215
|
+
usd = float(summary["est_usd_saved"])
|
|
216
|
+
events = int(summary["events"])
|
|
217
|
+
|
|
218
|
+
lines: List[str] = [
|
|
219
|
+
"┌────────────────────────────────────────────────────────────┐",
|
|
220
|
+
_box_row(f" AgentEfficiency Savings Receipt ({win})"),
|
|
221
|
+
"├────────────────────────────────────────────────────────────┤",
|
|
222
|
+
]
|
|
223
|
+
if events == 0:
|
|
224
|
+
lines.extend([
|
|
225
|
+
_box_row(" No savings recorded yet in this window."),
|
|
226
|
+
_box_row(" Try: `ae run -- pytest` or `ae slice path.py:func`"),
|
|
227
|
+
"└────────────────────────────────────────────────────────────┘",
|
|
228
|
+
])
|
|
229
|
+
return "\n".join(lines)
|
|
230
|
+
|
|
231
|
+
usd_str = f"${usd:.2f}" if usd >= 0.01 else f"${usd:.4f}"
|
|
232
|
+
lines.append(_box_row(f" Tokens saved : {_fmt_tok(saved):>8} tok (-{pct:4.1f}%) [~{usd_str}]"))
|
|
233
|
+
lines.append(_box_row(f" Raw -> Sent : {_fmt_tok(raw):>8} -> {_fmt_tok(out):<8} ({events} calls)"))
|
|
234
|
+
lines.append("├────────────────────────────────────────────────────────────┤")
|
|
235
|
+
max_saved = max((int(c["saved_tokens"]) for c in summary["by_command"]), default=1)
|
|
236
|
+
for item in summary["by_command"][:6]:
|
|
237
|
+
cmd_lbl = str(item["cmd"])[:10]
|
|
238
|
+
bar = _bar(item["saved_tokens"] / max(1, max_saved), width=16)
|
|
239
|
+
tok_s = _fmt_tok(int(item["saved_tokens"]))
|
|
240
|
+
pct_s = f"-{item['savings_pct']:.0f}%"
|
|
241
|
+
lines.append(_box_row(f" {cmd_lbl:<10} {bar} {tok_s:>7} ({pct_s:>4}, {item['calls']}x)"))
|
|
242
|
+
if summary.get("top_repos"):
|
|
243
|
+
repos_str = ", ".join(f"{r['repo']} ({_fmt_tok(r['saved_tokens'])})" for r in summary["top_repos"][:3])
|
|
244
|
+
lines.append("├────────────────────────────────────────────────────────────┤")
|
|
245
|
+
lines.append(_box_row(f" Top repos: {repos_str}"))
|
|
246
|
+
lines.append("├────────────────────────────────────────────────────────────┤")
|
|
247
|
+
lines.append(_box_row(" Note: gross I/O savings; check net cache hits: `ae audit`"))
|
|
248
|
+
lines.append("└────────────────────────────────────────────────────────────┘")
|
|
249
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Unified secret exclusion/redaction, path normalization, containment, and prompt-injection framing."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import posixpath
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import List, Set, Tuple
|
|
8
|
+
|
|
9
|
+
_BIDI_CTRL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\u202a-\u202e\u2066-\u2069\u200e\u200f]")
|
|
10
|
+
|
|
11
|
+
# Regular source code extensions where filenames like `credentials.py` or `secrets_manager.ts`
|
|
12
|
+
# represent code (not raw credential dumps). Hardcoded secrets inside them are still redacted.
|
|
13
|
+
SOURCE_CODE_EXTS: Set[str] = {
|
|
14
|
+
".py", ".pyi", ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts",
|
|
15
|
+
".java", ".kt", ".kts", ".go", ".rs", ".c", ".h", ".cpp", ".hpp", ".cc", ".hh",
|
|
16
|
+
".cs", ".php", ".rb", ".swift", ".scala", ".sh", ".bash", ".zsh", ".ps1", ".sql",
|
|
17
|
+
".vue", ".svelte", ".astro", ".dart", ".zig", ".lua", ".ex", ".exs", ".sol",
|
|
18
|
+
".groovy", ".md", ".mdx", ".rst",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
# Always secret regardless of extension (dotenv, private keys, terraform state/vars, auth dumps)
|
|
22
|
+
HARD_SECRET_PATH_RE = re.compile(
|
|
23
|
+
r"(^|/)("
|
|
24
|
+
r"\.env($|\.(?!example$|sample$|template$).*)"
|
|
25
|
+
r"|.*\.env($|\.(?!example$|sample$|template$).*)"
|
|
26
|
+
r"|\.envrc$"
|
|
27
|
+
r"|id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(\.|$)"
|
|
28
|
+
r"|.*\.(pem|key|p8|p12|pfx|jks|keystore|kdbx|ppk|gpg|asc|tfvars|tfvars\.json)$"
|
|
29
|
+
r"|.*\.tfstate(\.backup)?$"
|
|
30
|
+
r"|\.(npmrc|pypirc|netrc|htpasswd|git-credentials)$"
|
|
31
|
+
r"|.*service[-_]?account.*\.json$"
|
|
32
|
+
r"|(?:auth|local\.settings)\.json$"
|
|
33
|
+
r")",
|
|
34
|
+
re.IGNORECASE,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# Secret/credential filename heuristic applied to config/data/extensionless files (not source code)
|
|
38
|
+
SOFT_SECRET_NAME_RE = re.compile(
|
|
39
|
+
r"(^|/)(?:^|.*[./_-])(secrets?|credentials?|client_secret)(?:[./_-]|$)",
|
|
40
|
+
re.IGNORECASE,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# Backwards-compatible compiled pattern matching all hard secret paths + config/data secret names
|
|
44
|
+
SECRET_PATH_RE = re.compile(
|
|
45
|
+
r"(^|/)("
|
|
46
|
+
r"\.env($|\.(?!example$|sample$|template$).*)"
|
|
47
|
+
r"|.*\.env($|\.(?!example$|sample$|template$).*)"
|
|
48
|
+
r"|\.envrc$"
|
|
49
|
+
r"|id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(\.|$)"
|
|
50
|
+
r"|.*\.(pem|key|p8|p12|pfx|jks|keystore|kdbx|ppk|gpg|asc|tfvars|tfvars\.json)$"
|
|
51
|
+
r"|.*\.tfstate(\.backup)?$"
|
|
52
|
+
r"|\.(npmrc|pypirc|netrc|htpasswd|git-credentials)$"
|
|
53
|
+
r"|(?:^|.*[./_-])(secrets?|credentials?|client_secret)(?:[./_-]|$)"
|
|
54
|
+
r"|.*service[-_]?account.*\.json$"
|
|
55
|
+
r"|(?:auth|local\.settings)\.json$"
|
|
56
|
+
r")",
|
|
57
|
+
re.IGNORECASE,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
_ASSIGNMENT_KEYS = (
|
|
61
|
+
r"api[_-]?key|secret[_-]?key|client[_-]?secret|signing[_-]?secret"
|
|
62
|
+
r"|aws_secret_access_key|access[_-]?token|refresh[_-]?token"
|
|
63
|
+
r"|password|passwd|private[_-]?key|db_pass"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# Quoted string literal assignment: e.g. password = "SuperSecret123", "api_key": "abcd1234ef"
|
|
67
|
+
_QUOTED_SECRET_ASSIGN_RE = re.compile(
|
|
68
|
+
rf"""(?i)((?:{_ASSIGNMENT_KEYS})\s*['"]?\s*[:=]\s*)(['"])([^\s'"\n]{{8,}})\2"""
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
# Unquoted config/env assignment: e.g. password: supersecret123, AWS_SECRET_ACCESS_KEY=wJalrXU...
|
|
72
|
+
# Excludes expressions with (), [], {}, whitespace, or trailing punctuation so code is preserved.
|
|
73
|
+
_UNQUOTED_SECRET_ASSIGN_RE = re.compile(
|
|
74
|
+
rf"""(?i)((?:{_ASSIGNMENT_KEYS})\s*[:=]\s*)([^\s'"\n#;,(){{}}\[\]<>]{{8,}})"""
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# Code-expression / type-annotation / placeholder heuristics that must NOT be redacted
|
|
78
|
+
_CODE_EXPR_VALUE_RE = re.compile(
|
|
79
|
+
r"^(?:"
|
|
80
|
+
r"[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+" # dotted property/variable chain: pair.accessToken, self.token
|
|
81
|
+
r"|[A-Za-z_$][\w$]*::[A-Za-z_:]+" # Rust/C++ scoped path
|
|
82
|
+
r"|\$\{?[\w.-]+\}?" # shell/template var: $SECRET, ${API_KEY}
|
|
83
|
+
r"|process\.env\.[\w]+" # process.env.X
|
|
84
|
+
r"|(?:string|number|boolean|object|unknown|undefined|null|none|true|false|optional|str|int|bytes)"
|
|
85
|
+
r"|(?:replace[-_]?me|change[-_]?me|your[-_].*|example[-_].*|placeholder.*|dummy[-_].*|<[^>]+>)"
|
|
86
|
+
r")$",
|
|
87
|
+
re.IGNORECASE,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
_HIGH_CONFIDENCE_PATTERNS: Tuple[Tuple[re.Pattern[str], str], ...] = (
|
|
91
|
+
(re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----"), "[REDACTED_PRIVATE_KEY]"),
|
|
92
|
+
(re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----"), "[REDACTED_PRIVATE_KEY]"),
|
|
93
|
+
(
|
|
94
|
+
re.compile(
|
|
95
|
+
r"\b(?:"
|
|
96
|
+
r"sk-(?:proj-|ant-)?[A-Za-z0-9_-]{20,}"
|
|
97
|
+
r"|sk_(?:live|test)_[A-Za-z0-9]{16,}"
|
|
98
|
+
r"|rk_(?:live|test)_[A-Za-z0-9]{16,}"
|
|
99
|
+
r"|gh[pousr]_[A-Za-z0-9]{20,}"
|
|
100
|
+
r"|github_pat_[A-Za-z0-9_]{20,}"
|
|
101
|
+
r"|glpat-[A-Za-z0-9_-]{16,}"
|
|
102
|
+
r"|npm_[A-Za-z0-9]{20,}"
|
|
103
|
+
r"|pypi-[A-Za-z0-9_-]{20,}"
|
|
104
|
+
r"|hf_[A-Za-z0-9]{20,}"
|
|
105
|
+
r"|(?:AKIA|ASIA)[0-9A-Z]{16}"
|
|
106
|
+
r"|AIza[0-9A-Za-z_-]{30,}"
|
|
107
|
+
r"|xox[baprs]-[A-Za-z0-9-]{15,}"
|
|
108
|
+
r"|eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}"
|
|
109
|
+
r")\b"
|
|
110
|
+
),
|
|
111
|
+
"[REDACTED_TOKEN]",
|
|
112
|
+
),
|
|
113
|
+
(re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|basic)\s+)[A-Za-z0-9._~+/=-]{12,}"), r"\1[REDACTED_TOKEN]"),
|
|
114
|
+
(re.compile(r"(?i)((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp|https?)://[^:/@\s]{1,64}:)([^@\s]{4,})(@)"), r"\1[REDACTED_SECRET]\3"),
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
SECRET_CONTENT_PATTERNS: Tuple[Tuple[re.Pattern[str], str], ...] = (
|
|
118
|
+
*_HIGH_CONFIDENCE_PATTERNS,
|
|
119
|
+
(_QUOTED_SECRET_ASSIGN_RE, r"\1\2[REDACTED_SECRET]\2"),
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def is_secret_path(rel_path: str) -> bool:
|
|
124
|
+
"""Return True if a repo-relative path is a secret/credential file.
|
|
125
|
+
|
|
126
|
+
Always blocks `.env*` (except examples/templates), private keys, terraform vars/state,
|
|
127
|
+
service-account JSONs, etc. For `*secret*` / `*credential*` names, blocks config/data files
|
|
128
|
+
while allowing regular source code files (whose contents are still secret-redacted).
|
|
129
|
+
"""
|
|
130
|
+
norm = normalize_rel_path(rel_path)
|
|
131
|
+
if not norm:
|
|
132
|
+
return False
|
|
133
|
+
if HARD_SECRET_PATH_RE.search(norm):
|
|
134
|
+
return True
|
|
135
|
+
if SOFT_SECRET_NAME_RE.search(norm):
|
|
136
|
+
ext = Path(norm).suffix.lower()
|
|
137
|
+
if ext not in SOURCE_CODE_EXTS:
|
|
138
|
+
return True
|
|
139
|
+
return False
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _is_likely_code_value(val: str) -> bool:
|
|
143
|
+
if not val:
|
|
144
|
+
return True
|
|
145
|
+
if val.startswith("[REDACTED"):
|
|
146
|
+
return True
|
|
147
|
+
if _CODE_EXPR_VALUE_RE.match(val):
|
|
148
|
+
return True
|
|
149
|
+
# Snake-case / camelCase single-word identifier with no digits and no symbols (e.g. `my_password`, `userToken`)
|
|
150
|
+
if re.fullmatch(r"[a-z][a-z0-9_]*_[a-z0-9_]+", val) and not any(ch.isdigit() for ch in val):
|
|
151
|
+
return True
|
|
152
|
+
if re.fullmatch(r"[a-z]+(?:[A-Z][a-z]+)+", val):
|
|
153
|
+
return True
|
|
154
|
+
return False
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _redact_quoted_assign(m: re.Match[str]) -> str:
|
|
158
|
+
prefix, quote, val = m.group(1), m.group(2), m.group(3)
|
|
159
|
+
if _is_likely_code_value(val):
|
|
160
|
+
return m.group(0)
|
|
161
|
+
return f"{prefix}{quote}[REDACTED_SECRET]{quote}"
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _redact_unquoted_assign(m: re.Match[str]) -> str:
|
|
165
|
+
prefix, val = m.group(1), m.group(2)
|
|
166
|
+
# Check if followed by `(` or `[` in original string (function call or subscript like os.environ[...])
|
|
167
|
+
end_pos = m.end()
|
|
168
|
+
src = m.string
|
|
169
|
+
if end_pos < len(src) and src[end_pos] in ("(", "[", "."):
|
|
170
|
+
return m.group(0)
|
|
171
|
+
if _is_likely_code_value(val):
|
|
172
|
+
return m.group(0)
|
|
173
|
+
return f"{prefix}[REDACTED_SECRET]"
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def sanitize_inline(text: str) -> str:
|
|
177
|
+
return " ".join(_BIDI_CTRL_RE.sub("", text).splitlines()).strip()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def redact_secrets(text: str) -> str:
|
|
181
|
+
out = text
|
|
182
|
+
for pat, repl in _HIGH_CONFIDENCE_PATTERNS:
|
|
183
|
+
out = pat.sub(repl, out)
|
|
184
|
+
out = _QUOTED_SECRET_ASSIGN_RE.sub(_redact_quoted_assign, out)
|
|
185
|
+
out = _UNQUOTED_SECRET_ASSIGN_RE.sub(_redact_unquoted_assign, out)
|
|
186
|
+
return out
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def has_secret_leak(text: str) -> bool:
|
|
190
|
+
"""Return True if text contains any secret caught by `redact_secrets` (100% parity)."""
|
|
191
|
+
return redact_secrets(text) != text
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def find_secret_leak_lines(text: str) -> List[int]:
|
|
195
|
+
"""Return 1-indexed line numbers containing secrets (including multi-line private key headers)."""
|
|
196
|
+
lines: List[int] = []
|
|
197
|
+
for idx, line in enumerate(text.splitlines(), start=1):
|
|
198
|
+
if has_secret_leak(line):
|
|
199
|
+
lines.append(idx)
|
|
200
|
+
if not lines and has_secret_leak(text):
|
|
201
|
+
lines.append(1)
|
|
202
|
+
return lines
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def redact_secrets_with_flag(text: str) -> Tuple[str, bool]:
|
|
206
|
+
cleaned = _BIDI_CTRL_RE.sub("", text)
|
|
207
|
+
out = redact_secrets(cleaned)
|
|
208
|
+
return out, (out != cleaned)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def normalize_rel_path(raw: str) -> str:
|
|
212
|
+
"""Normalize a repo-relative path without stripping leading dots on dotfiles (`.env`, `.github`)."""
|
|
213
|
+
norm = raw.replace("\\", "/")
|
|
214
|
+
while norm.startswith("./"):
|
|
215
|
+
norm = norm[2:]
|
|
216
|
+
norm = norm.lstrip("/")
|
|
217
|
+
if not norm:
|
|
218
|
+
return ""
|
|
219
|
+
norm = posixpath.normpath(norm)
|
|
220
|
+
return "" if norm == "." else norm
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def is_within(path: Path, root: Path) -> bool:
|
|
224
|
+
try:
|
|
225
|
+
path.resolve().relative_to(root.resolve())
|
|
226
|
+
return True
|
|
227
|
+
except ValueError:
|
|
228
|
+
return False
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def frame_untrusted_data(label: str, text: str) -> str:
|
|
232
|
+
if not text:
|
|
233
|
+
return ""
|
|
234
|
+
safe = text.replace("</untrusted_repo_data>", "<\\/untrusted_repo_data>")
|
|
235
|
+
return f'<untrusted_repo_data layer="{label}">\n{safe.rstrip()}\n</untrusted_repo_data>\n'
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Unified LLM provider detection, pricing defaults, and multi-provider cache-usage normalization."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any, Dict, Optional, Tuple
|
|
6
|
+
|
|
7
|
+
PROVIDER_DEFAULTS: Dict[str, Dict[str, Any]] = {
|
|
8
|
+
"anthropic": {
|
|
9
|
+
"min_cache_tokens": 1024,
|
|
10
|
+
"default_ttl_seconds": 300,
|
|
11
|
+
"extended_ttl_seconds": 3600,
|
|
12
|
+
"cache_read_discount": 0.90,
|
|
13
|
+
"cache_write_premium": 0.25,
|
|
14
|
+
"extended_cache_write_premium": 1.00,
|
|
15
|
+
"max_breakpoints": 4,
|
|
16
|
+
},
|
|
17
|
+
"openai": {
|
|
18
|
+
"min_cache_tokens": 1024,
|
|
19
|
+
"default_ttl_seconds": 600,
|
|
20
|
+
"extended_ttl_seconds": 86400,
|
|
21
|
+
"cache_read_discount": 0.50,
|
|
22
|
+
"cache_write_premium": 0.0,
|
|
23
|
+
"extended_cache_write_premium": 0.0,
|
|
24
|
+
"max_breakpoints": 1,
|
|
25
|
+
},
|
|
26
|
+
"gemini": {
|
|
27
|
+
"min_cache_tokens": 1024,
|
|
28
|
+
"default_ttl_seconds": 3600,
|
|
29
|
+
"extended_ttl_seconds": 3600,
|
|
30
|
+
"cache_read_discount": 0.75,
|
|
31
|
+
"cache_write_premium": 0.0,
|
|
32
|
+
"extended_cache_write_premium": 0.0,
|
|
33
|
+
"max_breakpoints": 1,
|
|
34
|
+
},
|
|
35
|
+
"bedrock": {
|
|
36
|
+
"min_cache_tokens": 1024,
|
|
37
|
+
"default_ttl_seconds": 300,
|
|
38
|
+
"extended_ttl_seconds": 3600,
|
|
39
|
+
"cache_read_discount": 0.90,
|
|
40
|
+
"cache_write_premium": 0.25,
|
|
41
|
+
"extended_cache_write_premium": 0.25,
|
|
42
|
+
"max_breakpoints": 4,
|
|
43
|
+
},
|
|
44
|
+
"litellm": {
|
|
45
|
+
"min_cache_tokens": 1024,
|
|
46
|
+
"default_ttl_seconds": 300,
|
|
47
|
+
"extended_ttl_seconds": 3600,
|
|
48
|
+
"cache_read_discount": 0.75,
|
|
49
|
+
"cache_write_premium": 0.0,
|
|
50
|
+
"extended_cache_write_premium": 0.0,
|
|
51
|
+
"max_breakpoints": 4,
|
|
52
|
+
},
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
ALIAS_TO_TIER: Dict[str, str] = {
|
|
56
|
+
"fast": "low", "balanced": "medium", "reasoning": "high",
|
|
57
|
+
"low": "low", "medium": "medium", "high": "high", "critical": "critical",
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
# Realistic 2026 baseline per-1M pricing (USD): (input, cached_input_at_90pct, output)
|
|
61
|
+
# Haiku 4.5 ($1/$5), Sonnet 4.5/4.6 ($3/$15), Opus 4.5/4.6 ($15/$75 or $5/$25 — using $15/$75 high ceiling for conservative savings math? No: $5/$25 or $15/$75)
|
|
62
|
+
# Note: Keeping low=$1.00/1M so medium cached ($0.30/1M) < low uncached ($1.00/1M) -> cache-affinity hysteresis actually activates!
|
|
63
|
+
DEFAULT_TIER_PRICES: Dict[str, Tuple[float, float, float]] = {
|
|
64
|
+
"low": (1.0, 0.10, 5.0),
|
|
65
|
+
"medium": (3.0, 0.30, 15.0),
|
|
66
|
+
"high": (15.0, 1.50, 75.0),
|
|
67
|
+
"critical": (15.0, 1.50, 75.0),
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
_OPENAI_MODEL_RE = re.compile(r"(?:^|[/:\s-])(?:gpt|openai|o1|o3|o4)(?:$|[-._/\s0-9])", re.IGNORECASE)
|
|
71
|
+
_OPENAI_O_SERIES_RE = re.compile(r"(?:^|[/:\s-])o[134](?:$|[-._/\s])", re.IGNORECASE)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def min_cache_tokens_for_model(provider: str, model: str = "") -> int:
|
|
75
|
+
"""Return provider/model-specific minimum cacheable prefix threshold in tokens."""
|
|
76
|
+
prov = (provider or "anthropic").lower()
|
|
77
|
+
m = (model or "").lower()
|
|
78
|
+
if prov in ("anthropic", "bedrock"):
|
|
79
|
+
# Claude Haiku 4.5 and Opus 4.5 / 4.6 require 4,096 minimum tokens
|
|
80
|
+
if re.search(r"haiku[-_.\s]?4[._-]5|opus[-_.\s]?4[._-][56]", m):
|
|
81
|
+
return 4096
|
|
82
|
+
if "haiku" in m:
|
|
83
|
+
return 2048
|
|
84
|
+
return 1024
|
|
85
|
+
if prov == "gemini":
|
|
86
|
+
if "2.5-pro" in m or "2.5_pro" in m or "pro" in m:
|
|
87
|
+
return 2048
|
|
88
|
+
return 1024
|
|
89
|
+
return int(PROVIDER_DEFAULTS.get(prov, PROVIDER_DEFAULTS["litellm"])["min_cache_tokens"])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def detect_provider(model: str = "", explicit_provider: Optional[str] = None, default_when_empty: str = "anthropic") -> str:
|
|
93
|
+
if explicit_provider and explicit_provider in PROVIDER_DEFAULTS:
|
|
94
|
+
return explicit_provider
|
|
95
|
+
m = (model or "").lower().strip()
|
|
96
|
+
if "bedrock" in m:
|
|
97
|
+
return "bedrock"
|
|
98
|
+
if "claude" in m or "anthropic" in m:
|
|
99
|
+
return "anthropic"
|
|
100
|
+
if "gemini" in m or "vertex" in m or "google" in m:
|
|
101
|
+
return "gemini"
|
|
102
|
+
if "gpt" in m or "openai" in m or _OPENAI_O_SERIES_RE.search(m):
|
|
103
|
+
return "openai"
|
|
104
|
+
return explicit_provider or ("litellm" if model else default_when_empty)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def usage_to_dict(usage_obj: Any) -> Dict[str, Any]:
|
|
108
|
+
if usage_obj is None:
|
|
109
|
+
return {}
|
|
110
|
+
if isinstance(usage_obj, dict):
|
|
111
|
+
return usage_obj
|
|
112
|
+
for method in ("model_dump", "dict"):
|
|
113
|
+
fn = getattr(usage_obj, method, None)
|
|
114
|
+
if callable(fn):
|
|
115
|
+
try:
|
|
116
|
+
return dict(fn())
|
|
117
|
+
except Exception:
|
|
118
|
+
pass
|
|
119
|
+
try:
|
|
120
|
+
return dict(usage_obj)
|
|
121
|
+
except Exception:
|
|
122
|
+
pass
|
|
123
|
+
try:
|
|
124
|
+
return dict(vars(usage_obj))
|
|
125
|
+
except Exception:
|
|
126
|
+
return {}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def parse_provider_usage(usage: Dict[str, Any], provider: Optional[str] = None) -> Dict[str, Any]:
|
|
130
|
+
"""Normalize Anthropic, OpenAI (Chat + Responses API), Gemini (SDK + REST camelCase), Bedrock, and LiteLLM usage payloads."""
|
|
131
|
+
if not isinstance(usage, dict):
|
|
132
|
+
return {
|
|
133
|
+
"provider": provider, "input_tokens": 0, "cache_read_tokens": 0,
|
|
134
|
+
"cache_write_tokens": 0, "output_tokens": 0, "cache_verified": False, "cache_hit_rate_pct": 0.0,
|
|
135
|
+
}
|
|
136
|
+
ptd = usage_to_dict(usage.get("prompt_tokens_details"))
|
|
137
|
+
itd = usage_to_dict(usage.get("input_tokens_details"))
|
|
138
|
+
|
|
139
|
+
has_anth = usage.get("cache_read_input_tokens") is not None or usage.get("cache_creation_input_tokens") is not None
|
|
140
|
+
has_br = usage.get("cacheReadInputTokens") is not None or usage.get("cacheWriteInputTokens") is not None
|
|
141
|
+
has_gem_snake = usage.get("prompt_token_count") is not None or usage.get("cached_content_token_count") is not None
|
|
142
|
+
has_gem_camel = usage.get("promptTokenCount") is not None or usage.get("cachedContentTokenCount") is not None
|
|
143
|
+
has_oai = (
|
|
144
|
+
ptd.get("cached_tokens") is not None
|
|
145
|
+
or itd.get("cached_tokens") is not None
|
|
146
|
+
or usage.get("cached_tokens") is not None
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
if has_anth:
|
|
150
|
+
read_t = int(usage.get("cache_read_input_tokens") or 0)
|
|
151
|
+
write_t = int(usage.get("cache_creation_input_tokens") or 0)
|
|
152
|
+
if usage.get("input_tokens") is not None:
|
|
153
|
+
total_in = int(usage["input_tokens"]) + read_t + write_t
|
|
154
|
+
elif usage.get("prompt_tokens") is not None:
|
|
155
|
+
total_in = max(int(usage["prompt_tokens"]), read_t + write_t)
|
|
156
|
+
else:
|
|
157
|
+
total_in = read_t + write_t
|
|
158
|
+
out_t = int(usage.get("output_tokens") if usage.get("output_tokens") is not None else (usage.get("completion_tokens") or 0))
|
|
159
|
+
verified = True
|
|
160
|
+
elif has_br:
|
|
161
|
+
uncached = int(usage.get("inputTokens") if usage.get("inputTokens") is not None else (usage.get("input_tokens") or 0))
|
|
162
|
+
read_t = int(usage.get("cacheReadInputTokens") or 0)
|
|
163
|
+
write_t = int(usage.get("cacheWriteInputTokens") or 0)
|
|
164
|
+
total_in = uncached + read_t + write_t
|
|
165
|
+
out_t = int(usage.get("outputTokens") if usage.get("outputTokens") is not None else (usage.get("output_tokens") or 0))
|
|
166
|
+
verified = True
|
|
167
|
+
elif has_gem_snake or has_gem_camel:
|
|
168
|
+
total_in = int(usage.get("prompt_token_count") if usage.get("prompt_token_count") is not None else (usage.get("promptTokenCount") or 0))
|
|
169
|
+
raw_cached = usage.get("cached_content_token_count") if usage.get("cached_content_token_count") is not None else usage.get("cachedContentTokenCount")
|
|
170
|
+
read_t = int(raw_cached or 0)
|
|
171
|
+
write_t = 0
|
|
172
|
+
out_t = int(usage.get("candidates_token_count") if usage.get("candidates_token_count") is not None else (usage.get("candidatesTokenCount") or 0))
|
|
173
|
+
verified = raw_cached is not None
|
|
174
|
+
elif has_oai:
|
|
175
|
+
total_in = int(usage.get("prompt_tokens") if usage.get("prompt_tokens") is not None else (usage.get("input_tokens") or 0))
|
|
176
|
+
raw_cached = (
|
|
177
|
+
ptd.get("cached_tokens")
|
|
178
|
+
if ptd.get("cached_tokens") is not None
|
|
179
|
+
else (itd.get("cached_tokens") if itd.get("cached_tokens") is not None else usage.get("cached_tokens"))
|
|
180
|
+
)
|
|
181
|
+
read_t = int(raw_cached or 0)
|
|
182
|
+
write_t = 0
|
|
183
|
+
out_t = int(usage.get("completion_tokens") if usage.get("completion_tokens") is not None else (usage.get("output_tokens") or 0))
|
|
184
|
+
verified = True
|
|
185
|
+
else:
|
|
186
|
+
total_in = int(usage.get("prompt_tokens") if usage.get("prompt_tokens") is not None else (usage.get("input_tokens") or 0))
|
|
187
|
+
read_t = write_t = 0
|
|
188
|
+
out_t = int(usage.get("completion_tokens") if usage.get("completion_tokens") is not None else (usage.get("output_tokens") or 0))
|
|
189
|
+
verified = False
|
|
190
|
+
|
|
191
|
+
hit_rate = round((read_t / total_in) * 100.0, 2) if total_in > 0 else 0.0
|
|
192
|
+
return {
|
|
193
|
+
"provider": provider, "input_tokens": total_in, "cache_read_tokens": read_t,
|
|
194
|
+
"cache_write_tokens": write_t, "output_tokens": out_t, "cache_verified": verified, "cache_hit_rate_pct": hit_rate,
|
|
195
|
+
}
|