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.
Files changed (64) hide show
  1. agent_efficiency/__init__.py +15 -0
  2. agent_efficiency/_bundle/mcp/server.py +519 -0
  3. agent_efficiency/_bundle/rules/AGENT_RULES.md +9 -0
  4. agent_efficiency/_bundle/scripts/ae_cli.py +327 -0
  5. agent_efficiency/_bundle/scripts/ae_init.py +267 -0
  6. agent_efficiency/_bundle/scripts/ae_manage.py +578 -0
  7. agent_efficiency/_bundle/scripts/install.py +308 -0
  8. agent_efficiency/_bundle/scripts/pretool_hook.py +350 -0
  9. agent_efficiency/_bundle/scripts/render_demo_svg.py +180 -0
  10. agent_efficiency/_bundle/scripts/setup_hooks.py +330 -0
  11. agent_efficiency/_bundle/scripts/sync_shared.py +85 -0
  12. agent_efficiency/_bundle/scripts/validate_skills.py +150 -0
  13. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/SKILL.md +80 -0
  14. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/config/models.json +237 -0
  15. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/examples/workflow.md +77 -0
  16. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/routing-and-escalation.md +63 -0
  17. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/state-and-handoff.md +84 -0
  18. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/__init__.py +90 -0
  19. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/io_lock.py +199 -0
  20. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/savings.py +249 -0
  21. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/security.py +235 -0
  22. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/usage.py +195 -0
  23. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/agent_state.py +266 -0
  24. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/context_doctor.py +780 -0
  25. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/llm_adapter.py +306 -0
  26. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/route_task.py +496 -0
  27. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_ops.py +580 -0
  28. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_render.py +428 -0
  29. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_store.py +440 -0
  30. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/transcript_audit.py +854 -0
  31. agent_efficiency/_bundle/skills/local-context-index/SKILL.md +71 -0
  32. agent_efficiency/_bundle/skills/local-context-index/references/cli-reference.md +112 -0
  33. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/__init__.py +90 -0
  34. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/io_lock.py +199 -0
  35. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/savings.py +249 -0
  36. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/security.py +235 -0
  37. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/usage.py +195 -0
  38. agent_efficiency/_bundle/skills/local-context-index/scripts/compact_run.py +395 -0
  39. agent_efficiency/_bundle/skills/local-context-index/scripts/context_index.py +341 -0
  40. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_db.py +393 -0
  41. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_ignore.py +184 -0
  42. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_indexer.py +330 -0
  43. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_lsp.py +213 -0
  44. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_parsers.py +769 -0
  45. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_search.py +498 -0
  46. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_slice.py +610 -0
  47. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_trace.py +553 -0
  48. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_workspace.py +219 -0
  49. agent_efficiency/_bundle/skills/prompt-cache-manager/SKILL.md +52 -0
  50. agent_efficiency/_bundle/skills/prompt-cache-manager/references/provider-caching.md +52 -0
  51. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/__init__.py +90 -0
  52. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/io_lock.py +199 -0
  53. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/savings.py +249 -0
  54. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/security.py +235 -0
  55. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/usage.py +195 -0
  56. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/cache_payload.py +278 -0
  57. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/prompt_cache.py +488 -0
  58. agent_efficiency/cli.py +23 -0
  59. agent_efficiency/mcp_entry.py +25 -0
  60. agent_efficiency-1.4.2.dist-info/METADATA +267 -0
  61. agent_efficiency-1.4.2.dist-info/RECORD +64 -0
  62. agent_efficiency-1.4.2.dist-info/WHEEL +4 -0
  63. agent_efficiency-1.4.2.dist-info/entry_points.txt +4 -0
  64. agent_efficiency-1.4.2.dist-info/licenses/LICENSE +21 -0
@@ -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
+ }