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,488 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""AgentEfficiency — Persistent prompt-cache registry, warm-TTL tracker, telemetry sync & CLI.
|
|
3
|
+
|
|
4
|
+
Delegates linting, diffing, layer assembly, and provider payload building to `cache_payload.py`
|
|
5
|
+
and shared locking/usage/redaction primitives to `_ae_core`.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
import stat
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Dict, List, Optional, Sequence
|
|
17
|
+
|
|
18
|
+
_SCRIPT_DIR = str(Path(__file__).resolve().parent)
|
|
19
|
+
if _SCRIPT_DIR not in sys.path:
|
|
20
|
+
sys.path.insert(0, _SCRIPT_DIR)
|
|
21
|
+
|
|
22
|
+
from _ae_core import ( # noqa: E402, F401
|
|
23
|
+
ALIAS_TO_TIER,
|
|
24
|
+
DEFAULT_TIER_PRICES,
|
|
25
|
+
PROVIDER_DEFAULTS,
|
|
26
|
+
atomic_write_json,
|
|
27
|
+
canonicalize_text,
|
|
28
|
+
compute_prefix_id,
|
|
29
|
+
detect_provider,
|
|
30
|
+
estimate_tokens,
|
|
31
|
+
file_lock,
|
|
32
|
+
is_within,
|
|
33
|
+
parse_provider_usage as parse_usage,
|
|
34
|
+
redact_secrets,
|
|
35
|
+
sha256_text,
|
|
36
|
+
)
|
|
37
|
+
from cache_payload import ( # noqa: E402, F401
|
|
38
|
+
MAX_SOURCE_FILE_BYTES,
|
|
39
|
+
assemble_layers,
|
|
40
|
+
build_provider_payload,
|
|
41
|
+
diff_prefixes,
|
|
42
|
+
lint_prefix,
|
|
43
|
+
read_safe_source,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
REGISTRY_SCHEMA_VERSION = 1
|
|
47
|
+
VALID_PREFIX_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _normalize_tier(val: str) -> str:
|
|
51
|
+
return ALIAS_TO_TIER.get((val or "").lower(), "medium")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _validate_prefix_name(name: str) -> str:
|
|
55
|
+
if not VALID_PREFIX_NAME_RE.fullmatch(name) or ".." in name:
|
|
56
|
+
raise SystemExit(f"Invalid prefix name {name!r}: use letters, digits, '_', '-', '.' (no '..').")
|
|
57
|
+
return name
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _safe_state_dir(repo: Path) -> Path:
|
|
61
|
+
repo_r = repo.resolve()
|
|
62
|
+
sd = repo_r / ".agent-state"
|
|
63
|
+
if sd.is_symlink() or (sd.exists() and not is_within(sd, repo_r)):
|
|
64
|
+
raise SystemExit("Refusing to use symlinked or out-of-repo .agent-state directory.")
|
|
65
|
+
return sd
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _registry_path(repo: Path) -> Path:
|
|
69
|
+
rp = _safe_state_dir(repo) / "cache_registry.json"
|
|
70
|
+
if rp.is_symlink():
|
|
71
|
+
raise SystemExit("Refusing to follow symlinked cache_registry.json.")
|
|
72
|
+
return rp
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _snapshot_path(repo: Path, name: str) -> Path:
|
|
76
|
+
safe_name = _validate_prefix_name(name)
|
|
77
|
+
snaps_dir = _safe_state_dir(repo) / "cache" / "snapshots"
|
|
78
|
+
sp = (snaps_dir / f"{safe_name}.json").resolve()
|
|
79
|
+
if not is_within(sp, snaps_dir) or sp.is_symlink():
|
|
80
|
+
raise SystemExit(f"Unsafe snapshot path for prefix {name!r}.")
|
|
81
|
+
return sp
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _empty_totals() -> Dict[str, Any]:
|
|
85
|
+
return {"calls": 0, "verified_cache_hits": 0, "cache_misses": 0, "input_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "output_tokens": 0, "estimated_savings_usd": 0.0}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def load_registry(repo: Path) -> Dict[str, Any]:
|
|
89
|
+
path = _registry_path(repo)
|
|
90
|
+
if not path.is_file():
|
|
91
|
+
return {"schema_version": REGISTRY_SCHEMA_VERSION, "prefixes": {}, "totals": _empty_totals()}
|
|
92
|
+
try:
|
|
93
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
94
|
+
if not isinstance(data, dict):
|
|
95
|
+
return {"schema_version": REGISTRY_SCHEMA_VERSION, "prefixes": {}, "totals": _empty_totals()}
|
|
96
|
+
data.setdefault("prefixes", {})
|
|
97
|
+
tot = data.setdefault("totals", {})
|
|
98
|
+
for k, v in _empty_totals().items():
|
|
99
|
+
tot.setdefault(k, v)
|
|
100
|
+
return data
|
|
101
|
+
except Exception:
|
|
102
|
+
return {"schema_version": REGISTRY_SCHEMA_VERSION, "prefixes": {}, "totals": _empty_totals()}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def register_prefix(
|
|
106
|
+
repo: Path,
|
|
107
|
+
name: str,
|
|
108
|
+
l0_static: str,
|
|
109
|
+
l1_project: str = "",
|
|
110
|
+
source_hashes: Optional[Dict[str, str]] = None,
|
|
111
|
+
provider: Optional[str] = None,
|
|
112
|
+
model: str = "",
|
|
113
|
+
ttl_seconds: Optional[int] = None,
|
|
114
|
+
external_cache_id: Optional[str] = None,
|
|
115
|
+
strict: bool = False,
|
|
116
|
+
) -> Dict[str, Any]:
|
|
117
|
+
repo = repo.resolve()
|
|
118
|
+
_validate_prefix_name(name)
|
|
119
|
+
raw_l0, raw_l1 = canonicalize_text(l0_static), canonicalize_text(l1_project)
|
|
120
|
+
lint = lint_prefix(raw_l0, raw_l1, provider=provider, model=model)
|
|
121
|
+
if strict and not lint["ok"]:
|
|
122
|
+
raise SystemExit(f"Prefix failed strict cache-buster lint: {json.dumps(lint['issues'], indent=2)}")
|
|
123
|
+
|
|
124
|
+
l0, l1 = canonicalize_text(redact_secrets(raw_l0)), canonicalize_text(redact_secrets(raw_l1))
|
|
125
|
+
prefix_id, combined_sha = compute_prefix_id(l0, l1)
|
|
126
|
+
now_ts = time.time()
|
|
127
|
+
sd = _safe_state_dir(repo)
|
|
128
|
+
snap_path = _snapshot_path(repo, name)
|
|
129
|
+
invalidation: Optional[Dict[str, Any]] = None
|
|
130
|
+
|
|
131
|
+
with file_lock(sd / ".cache.lock"):
|
|
132
|
+
reg = load_registry(repo)
|
|
133
|
+
prev = reg["prefixes"].get(name)
|
|
134
|
+
changed = bool(prev and prev.get("prefix_id") != prefix_id)
|
|
135
|
+
if prev and snap_path.is_file():
|
|
136
|
+
try:
|
|
137
|
+
old_snap = json.loads(snap_path.read_text(encoding="utf-8"))
|
|
138
|
+
invalidation = diff_prefixes(old_snap.get("l0_static", ""), old_snap.get("l1_project", ""), l0, l1)
|
|
139
|
+
except Exception:
|
|
140
|
+
invalidation = None
|
|
141
|
+
|
|
142
|
+
prov = detect_provider(model, provider)
|
|
143
|
+
ttl = int(ttl_seconds or PROVIDER_DEFAULTS.get(prov, PROVIDER_DEFAULTS["litellm"])["default_ttl_seconds"])
|
|
144
|
+
sessions = {k: dict(v) for k, v in prev.get("sessions", {}).items()} if prev else {}
|
|
145
|
+
if changed:
|
|
146
|
+
for s in sessions.values():
|
|
147
|
+
s["expires_at"] = None
|
|
148
|
+
|
|
149
|
+
if model or external_cache_id:
|
|
150
|
+
skey = f"{prov}:{model or 'default'}"
|
|
151
|
+
ex = sessions.get(skey, {})
|
|
152
|
+
if ex and not changed and ex.get("prefix_id") == prefix_id:
|
|
153
|
+
ex["ttl_seconds"] = ttl
|
|
154
|
+
if external_cache_id:
|
|
155
|
+
ex["external_cache_id"] = external_cache_id
|
|
156
|
+
sessions[skey] = ex
|
|
157
|
+
else:
|
|
158
|
+
sessions[skey] = {
|
|
159
|
+
"provider": prov, "model": model or "default", "prefix_id": prefix_id,
|
|
160
|
+
"tier": ex.get("tier", "medium"), "ttl_seconds": ttl,
|
|
161
|
+
"external_cache_id": external_cache_id or (ex.get("external_cache_id") if not changed else None),
|
|
162
|
+
"registered_at": now_ts, "last_used_at": None, "expires_at": None,
|
|
163
|
+
"hits": ex.get("hits", 0), "misses": ex.get("misses", 0),
|
|
164
|
+
"cache_read_tokens": ex.get("cache_read_tokens", 0), "cache_write_tokens": ex.get("cache_write_tokens", 0),
|
|
165
|
+
"input_tokens": ex.get("input_tokens", 0), "output_tokens": ex.get("output_tokens", 0),
|
|
166
|
+
"estimated_savings_usd": ex.get("estimated_savings_usd", 0.0),
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
entry = {
|
|
170
|
+
"name": name, "prefix_id": prefix_id, "l0_sha": sha256_text(l0)[:16], "l1_sha": sha256_text(l1)[:16],
|
|
171
|
+
"combined_sha": combined_sha[:24], "l0_tokens_est": estimate_tokens(l0), "l1_tokens_est": estimate_tokens(l1),
|
|
172
|
+
"combined_tokens_est": estimate_tokens(l0) + estimate_tokens(l1), "source_files": source_hashes or {},
|
|
173
|
+
"lint_ok": lint["ok"], "cacheable": lint["cacheable"],
|
|
174
|
+
"version": (prev.get("version", 0) + 1) if changed else (prev.get("version", 1) if prev else 1),
|
|
175
|
+
"updated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "updated_epoch": now_ts, "sessions": sessions,
|
|
176
|
+
}
|
|
177
|
+
reg["prefixes"][name] = entry
|
|
178
|
+
reg["updated_at"] = entry["updated_at"]
|
|
179
|
+
atomic_write_json(_registry_path(repo), reg, sort_keys=True)
|
|
180
|
+
atomic_write_json(snap_path, {"name": name, "prefix_id": prefix_id, "l0_static": l0, "l1_project": l1}, sort_keys=True)
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
"name": name, "prefix_id": prefix_id, "version": entry["version"],
|
|
184
|
+
"l0_tokens_est": entry["l0_tokens_est"], "l1_tokens_est": entry["l1_tokens_est"],
|
|
185
|
+
"combined_tokens_est": entry["combined_tokens_est"], "lint": lint,
|
|
186
|
+
"invalidation": invalidation, "registry_path": str(_registry_path(repo)),
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _sync_state_telemetry(
|
|
191
|
+
sd: Path,
|
|
192
|
+
norm_tier: str,
|
|
193
|
+
parsed: Dict[str, Any],
|
|
194
|
+
read_disc: float,
|
|
195
|
+
write_prem: float,
|
|
196
|
+
input_price_override: Optional[float] = None,
|
|
197
|
+
) -> None:
|
|
198
|
+
sf = sd / "state.json"
|
|
199
|
+
if not sf.is_file() or sf.is_symlink():
|
|
200
|
+
return
|
|
201
|
+
try:
|
|
202
|
+
with file_lock(sd / ".state.lock"):
|
|
203
|
+
st = json.loads(sf.read_text(encoding="utf-8"))
|
|
204
|
+
telem = st.setdefault("telemetry", {})
|
|
205
|
+
for k, dv in (("calls", 0), ("input_tokens", 0), ("cached_input_tokens", 0), ("cache_write_tokens", 0), ("output_tokens", 0), ("estimated_cost_usd", 0.0), ("estimated_savings_vs_uncached_reasoning_usd", 0.0), ("model_switches", 0)):
|
|
206
|
+
telem.setdefault(k, dv)
|
|
207
|
+
by_tier = telem.setdefault("by_tier", {})
|
|
208
|
+
p_in_def, _p_cached_def, p_out = DEFAULT_TIER_PRICES[norm_tier]
|
|
209
|
+
p_in = input_price_override if input_price_override is not None else p_in_def
|
|
210
|
+
eff_cached = p_in * (1.0 - read_disc)
|
|
211
|
+
actual = (
|
|
212
|
+
max(0, parsed["input_tokens"] - parsed["cache_read_tokens"]) * p_in
|
|
213
|
+
+ parsed["cache_read_tokens"] * eff_cached
|
|
214
|
+
+ parsed["cache_write_tokens"] * (p_in * write_prem)
|
|
215
|
+
+ parsed["output_tokens"] * p_out
|
|
216
|
+
) / 1_000_000.0
|
|
217
|
+
r_in, _rc, r_out = DEFAULT_TIER_PRICES["high"]
|
|
218
|
+
vs_base = max(0.0, (parsed["input_tokens"] * r_in + parsed["output_tokens"] * r_out) / 1_000_000.0 - actual)
|
|
219
|
+
telem["calls"] += 1
|
|
220
|
+
telem["input_tokens"] += parsed["input_tokens"]
|
|
221
|
+
telem["cached_input_tokens"] += parsed["cache_read_tokens"]
|
|
222
|
+
telem["cache_write_tokens"] += parsed["cache_write_tokens"]
|
|
223
|
+
telem["output_tokens"] += parsed["output_tokens"]
|
|
224
|
+
telem["estimated_cost_usd"] = round(float(telem["estimated_cost_usd"]) + actual, 6)
|
|
225
|
+
telem["estimated_savings_vs_uncached_reasoning_usd"] = round(float(telem["estimated_savings_vs_uncached_reasoning_usd"]) + vs_base, 6)
|
|
226
|
+
tb = by_tier.setdefault(norm_tier, {"calls": 0, "input_tokens": 0, "cached_tokens": 0, "output_tokens": 0})
|
|
227
|
+
tb["calls"] += 1
|
|
228
|
+
tb["input_tokens"] += parsed["input_tokens"]
|
|
229
|
+
tb["cached_tokens"] += parsed["cache_read_tokens"]
|
|
230
|
+
tb["output_tokens"] += parsed["output_tokens"]
|
|
231
|
+
st["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
|
|
232
|
+
atomic_write_json(sf, st)
|
|
233
|
+
except Exception:
|
|
234
|
+
pass
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def record_usage(
|
|
238
|
+
repo: Path,
|
|
239
|
+
name: str,
|
|
240
|
+
provider: Optional[str],
|
|
241
|
+
model: str,
|
|
242
|
+
usage: Dict[str, Any],
|
|
243
|
+
tier: str = "medium",
|
|
244
|
+
ttl_seconds: Optional[int] = None,
|
|
245
|
+
external_cache_id: Optional[str] = None,
|
|
246
|
+
input_price_per_1m: Optional[float] = None,
|
|
247
|
+
) -> Dict[str, Any]:
|
|
248
|
+
repo = repo.resolve()
|
|
249
|
+
_validate_prefix_name(name)
|
|
250
|
+
norm_tier = _normalize_tier(tier)
|
|
251
|
+
prov = detect_provider(model, provider)
|
|
252
|
+
pinfo = PROVIDER_DEFAULTS.get(prov, PROVIDER_DEFAULTS["litellm"])
|
|
253
|
+
parsed = parse_usage(usage, provider=prov)
|
|
254
|
+
now_ts = time.time()
|
|
255
|
+
ttl = int(ttl_seconds or pinfo["default_ttl_seconds"])
|
|
256
|
+
unit_price = input_price_per_1m if input_price_per_1m is not None else DEFAULT_TIER_PRICES[norm_tier][0]
|
|
257
|
+
read_disc = float(pinfo["cache_read_discount"])
|
|
258
|
+
is_extended_ttl = ttl >= int(pinfo.get("extended_ttl_seconds", 3600)) and int(pinfo.get("extended_ttl_seconds", 3600)) > int(pinfo.get("default_ttl_seconds", 300))
|
|
259
|
+
write_prem = float(pinfo["extended_cache_write_premium"] if is_extended_ttl else pinfo["cache_write_premium"])
|
|
260
|
+
net_savings = (parsed["cache_read_tokens"] * unit_price * read_disc - parsed["cache_write_tokens"] * unit_price * write_prem) / 1_000_000.0
|
|
261
|
+
warning: Optional[str] = None
|
|
262
|
+
|
|
263
|
+
sd = _safe_state_dir(repo)
|
|
264
|
+
with file_lock(sd / ".cache.lock"):
|
|
265
|
+
reg = load_registry(repo)
|
|
266
|
+
entry = reg["prefixes"].setdefault(
|
|
267
|
+
name,
|
|
268
|
+
{"name": name, "prefix_id": f"pfx-unregistered-{name}", "l0_tokens_est": 0, "l1_tokens_est": 0, "combined_tokens_est": parsed["cache_read_tokens"] or parsed["cache_write_tokens"], "source_files": {}, "version": 1, "sessions": {}},
|
|
269
|
+
)
|
|
270
|
+
reg_tok = int(entry.get("combined_tokens_est", 0))
|
|
271
|
+
if reg_tok > 0 and parsed["cache_read_tokens"] > reg_tok * 2:
|
|
272
|
+
warning = f"Reported cache_read_tokens ({parsed['cache_read_tokens']}) exceeds registered prefix estimate (~{reg_tok} tok) by >2x; verify usage matches prefix '{name}'."
|
|
273
|
+
|
|
274
|
+
skey = f"{prov}:{model or 'default'}"
|
|
275
|
+
sess = entry.setdefault("sessions", {}).setdefault(
|
|
276
|
+
skey, {"provider": prov, "model": model or "default", "prefix_id": entry.get("prefix_id"), "tier": norm_tier, "ttl_seconds": ttl, "external_cache_id": external_cache_id, "hits": 0, "misses": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "input_tokens": 0, "output_tokens": 0, "estimated_savings_usd": 0.0}
|
|
277
|
+
)
|
|
278
|
+
sess.update({"prefix_id": entry.get("prefix_id"), "tier": norm_tier, "ttl_seconds": ttl, "last_used_at": now_ts, "expires_at": now_ts + ttl})
|
|
279
|
+
if external_cache_id:
|
|
280
|
+
sess["external_cache_id"] = external_cache_id
|
|
281
|
+
is_hit = parsed["cache_verified"] and parsed["cache_read_tokens"] > 0
|
|
282
|
+
sess["hits" if is_hit else "misses"] = int(sess.get("hits" if is_hit else "misses", 0)) + 1
|
|
283
|
+
sess["cache_read_tokens"] += parsed["cache_read_tokens"]
|
|
284
|
+
sess["cache_write_tokens"] += parsed["cache_write_tokens"]
|
|
285
|
+
sess["input_tokens"] += parsed["input_tokens"]
|
|
286
|
+
sess["output_tokens"] += parsed["output_tokens"]
|
|
287
|
+
sess["estimated_savings_usd"] = round(float(sess.get("estimated_savings_usd", 0.0)) + net_savings, 6)
|
|
288
|
+
|
|
289
|
+
tot = reg["totals"]
|
|
290
|
+
tot["calls"] += 1
|
|
291
|
+
tot["verified_cache_hits" if is_hit else "cache_misses"] += 1
|
|
292
|
+
tot["input_tokens"] += parsed["input_tokens"]
|
|
293
|
+
tot["cache_read_tokens"] += parsed["cache_read_tokens"]
|
|
294
|
+
tot["cache_write_tokens"] += parsed["cache_write_tokens"]
|
|
295
|
+
tot["output_tokens"] += parsed["output_tokens"]
|
|
296
|
+
tot["estimated_savings_usd"] = round(float(tot.get("estimated_savings_usd", 0.0)) + net_savings, 6)
|
|
297
|
+
reg["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
|
|
298
|
+
atomic_write_json(_registry_path(repo), reg, sort_keys=True)
|
|
299
|
+
|
|
300
|
+
_sync_state_telemetry(sd, norm_tier, parsed, read_disc, write_prem, input_price_override=input_price_per_1m)
|
|
301
|
+
res: Dict[str, Any] = {
|
|
302
|
+
"name": name, "provider": prov, "model": model, "tier": norm_tier, "cache_hit": is_hit,
|
|
303
|
+
"parsed_usage": parsed, "net_savings_usd": round(net_savings, 6),
|
|
304
|
+
"warm_until_epoch": now_ts + ttl, "ttl_seconds": ttl,
|
|
305
|
+
}
|
|
306
|
+
if warning:
|
|
307
|
+
res["warning"] = warning
|
|
308
|
+
return res
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _stale_sources_for_entry(repo: Path, entry: Dict[str, Any]) -> List[str]:
|
|
312
|
+
stale: List[str] = []
|
|
313
|
+
repo_r = repo.resolve()
|
|
314
|
+
for rel, old_sha in entry.get("source_files", {}).items():
|
|
315
|
+
cand = Path(rel)
|
|
316
|
+
if cand.is_absolute():
|
|
317
|
+
stale.append(f"external_unverified:{rel}")
|
|
318
|
+
continue
|
|
319
|
+
fp = (repo_r / cand).resolve()
|
|
320
|
+
if (repo_r / cand).is_symlink() or not is_within(fp, repo_r):
|
|
321
|
+
stale.append(f"unsafe:{rel}")
|
|
322
|
+
elif not fp.exists():
|
|
323
|
+
stale.append(f"missing:{rel}")
|
|
324
|
+
else:
|
|
325
|
+
try:
|
|
326
|
+
st = fp.stat()
|
|
327
|
+
if not stat.S_ISREG(st.st_mode) or st.st_size > MAX_SOURCE_FILE_BYTES:
|
|
328
|
+
stale.append(f"unreadable:{rel}")
|
|
329
|
+
continue
|
|
330
|
+
cur = fp.read_text(encoding="utf-8", errors="replace")
|
|
331
|
+
except OSError:
|
|
332
|
+
stale.append(f"unreadable:{rel}")
|
|
333
|
+
continue
|
|
334
|
+
if rel.endswith("DECISIONS.md"):
|
|
335
|
+
cur = cur.split("## Superseded / Archived Decisions", 1)[0].strip()
|
|
336
|
+
if sha256_text(cur)[:16] != old_sha:
|
|
337
|
+
stale.append(f"modified:{rel}")
|
|
338
|
+
return stale
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def cache_status(repo: Path, name: Optional[str] = None) -> Dict[str, Any]:
|
|
342
|
+
repo = repo.resolve()
|
|
343
|
+
reg = load_registry(repo)
|
|
344
|
+
now_ts = time.time()
|
|
345
|
+
prefixes_out: List[Dict[str, Any]] = []
|
|
346
|
+
items = [(name, reg["prefixes"][name])] if (name and name in reg["prefixes"]) else sorted(reg["prefixes"].items())
|
|
347
|
+
for pname, entry in items:
|
|
348
|
+
stale = _stale_sources_for_entry(repo, entry)
|
|
349
|
+
cur_pid = entry.get("prefix_id")
|
|
350
|
+
sessions_out = []
|
|
351
|
+
for skey, s in sorted(entry.get("sessions", {}).items()):
|
|
352
|
+
exp = s.get("expires_at")
|
|
353
|
+
rem = max(0, int(exp - now_ts)) if exp else 0
|
|
354
|
+
id_ok = not s.get("prefix_id") or s.get("prefix_id") == cur_pid
|
|
355
|
+
warm = rem > 0 and id_ok and not stale
|
|
356
|
+
sessions_out.append({
|
|
357
|
+
"session": skey, "tier": s.get("tier"),
|
|
358
|
+
"status": "warm" if warm else ("stale_source" if (rem > 0 and id_ok and stale) else "cold"),
|
|
359
|
+
"ttl_remaining_seconds": rem if id_ok else 0, "external_cache_id": s.get("external_cache_id"),
|
|
360
|
+
"hits": s.get("hits", 0), "misses": s.get("misses", 0),
|
|
361
|
+
"cache_read_tokens": s.get("cache_read_tokens", 0), "estimated_savings_usd": s.get("estimated_savings_usd", 0.0),
|
|
362
|
+
})
|
|
363
|
+
prefixes_out.append({"name": pname, "prefix_id": cur_pid, "version": entry.get("version", 1), "combined_tokens_est": entry.get("combined_tokens_est", 0), "cacheable": entry.get("cacheable", False), "stale_sources": stale, "sessions": sessions_out})
|
|
364
|
+
|
|
365
|
+
tot = reg["totals"]
|
|
366
|
+
hit_pct = round((tot["cache_read_tokens"] / tot["input_tokens"]) * 100.0, 2) if tot["input_tokens"] > 0 else 0.0
|
|
367
|
+
return {"registry_path": str(_registry_path(repo)), "prefix_count": len(prefixes_out), "totals": {**tot, "overall_cache_read_pct": hit_pct}, "prefixes": prefixes_out}
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def get_warm_cache_hint(repo: Path) -> Optional[Dict[str, Any]]:
|
|
371
|
+
best: Optional[Dict[str, Any]] = None
|
|
372
|
+
for p in cache_status(repo)["prefixes"]:
|
|
373
|
+
if p["stale_sources"]:
|
|
374
|
+
continue
|
|
375
|
+
for s in p["sessions"]:
|
|
376
|
+
if s["status"] == "warm":
|
|
377
|
+
cand = {"prefix_name": p["name"], "prefix_id": p["prefix_id"], "prefix_tokens": p["combined_tokens_est"], "tier": _normalize_tier(s.get("tier") or "medium"), "session": s["session"], "ttl_remaining_seconds": s["ttl_remaining_seconds"]}
|
|
378
|
+
if best is None or cand["prefix_tokens"] > best["prefix_tokens"]:
|
|
379
|
+
best = cand
|
|
380
|
+
return best
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
384
|
+
ap = argparse.ArgumentParser(description="AgentEfficiency deterministic prompt-cache manager.")
|
|
385
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
386
|
+
|
|
387
|
+
for cname, needs_repo in (("lint", False), ("register", True), ("diff", True)):
|
|
388
|
+
p = sub.add_parser(cname, help=f"{cname.title()} prompt prefix layers")
|
|
389
|
+
if needs_repo:
|
|
390
|
+
p.add_argument("repo", type=Path)
|
|
391
|
+
else:
|
|
392
|
+
p.add_argument("repo_pos", nargs="?", type=Path, default=None)
|
|
393
|
+
p.add_argument("--repo", type=Path, default=None)
|
|
394
|
+
if cname in ("register", "diff"):
|
|
395
|
+
p.add_argument("--name", required=True)
|
|
396
|
+
p.add_argument("--l0-text", default="")
|
|
397
|
+
p.add_argument("--l1-text", default="")
|
|
398
|
+
p.add_argument("--l0-file", action="append", default=[])
|
|
399
|
+
p.add_argument("--l1-file", action="append", default=[])
|
|
400
|
+
p.add_argument("--include-map", action="store_true")
|
|
401
|
+
p.add_argument("--include-decisions", action="store_true")
|
|
402
|
+
p.add_argument("--allow-external", action="store_true")
|
|
403
|
+
if cname in ("lint", "register"):
|
|
404
|
+
p.add_argument("--provider", choices=sorted(PROVIDER_DEFAULTS.keys()), default=None)
|
|
405
|
+
p.add_argument("--model", default="")
|
|
406
|
+
p.add_argument("--strict", action="store_true")
|
|
407
|
+
if cname == "register":
|
|
408
|
+
p.add_argument("--ttl", type=int, default=None)
|
|
409
|
+
p.add_argument("--external-cache-id", default=None)
|
|
410
|
+
|
|
411
|
+
p = sub.add_parser("build-payload", help="Build provider-native prompt-cached payload")
|
|
412
|
+
p.add_argument("repo_pos", nargs="?", type=Path, default=None, help="Optional positional repository path (alternative to --repo)")
|
|
413
|
+
p.add_argument("--repo", type=Path, default=None)
|
|
414
|
+
p.add_argument("--name", default=None)
|
|
415
|
+
p.add_argument("--l0-text", default="")
|
|
416
|
+
p.add_argument("--l1-text", default="")
|
|
417
|
+
p.add_argument("--volatile-text", default="")
|
|
418
|
+
p.add_argument("--volatile-file", action="append", default=[])
|
|
419
|
+
p.add_argument("--allow-external", action="store_true")
|
|
420
|
+
p.add_argument("--user-task", required=True)
|
|
421
|
+
p.add_argument("--provider", choices=sorted(PROVIDER_DEFAULTS.keys()), default=None)
|
|
422
|
+
p.add_argument("--model", default="")
|
|
423
|
+
p.add_argument("--ttl", choices=["5m", "1h"], default="5m")
|
|
424
|
+
p.add_argument("--retention", choices=["in_memory", "24h"], default="in_memory")
|
|
425
|
+
p.add_argument("--strict", action="store_true")
|
|
426
|
+
|
|
427
|
+
p = sub.add_parser("record-usage", help="Record verified provider cache usage metadata")
|
|
428
|
+
p.add_argument("repo", type=Path)
|
|
429
|
+
p.add_argument("--name", required=True)
|
|
430
|
+
p.add_argument("--provider", choices=sorted(PROVIDER_DEFAULTS.keys()), default=None)
|
|
431
|
+
p.add_argument("--model", default="")
|
|
432
|
+
p.add_argument("--tier", default="medium")
|
|
433
|
+
p.add_argument("--usage-json", required=True)
|
|
434
|
+
p.add_argument("--ttl", type=int, default=None)
|
|
435
|
+
p.add_argument("--external-cache-id", default=None)
|
|
436
|
+
p.add_argument("--input-price-per-1m", type=float, default=None)
|
|
437
|
+
|
|
438
|
+
p = sub.add_parser("status", help="Inspect registered prefixes, warm TTLs, staleness & savings")
|
|
439
|
+
p.add_argument("repo", type=Path)
|
|
440
|
+
p.add_argument("--name", default=None)
|
|
441
|
+
|
|
442
|
+
args = ap.parse_args(argv)
|
|
443
|
+
|
|
444
|
+
if args.cmd == "lint":
|
|
445
|
+
repo_arg = args.repo or args.repo_pos
|
|
446
|
+
l0, l1, _ = assemble_layers(repo_arg, args.l0_text, args.l1_text, args.l0_file, args.l1_file, args.include_map, args.include_decisions, args.allow_external, redact=False)
|
|
447
|
+
res = lint_prefix(l0, l1, provider=args.provider, model=args.model)
|
|
448
|
+
print(json.dumps(res, indent=2, ensure_ascii=False))
|
|
449
|
+
return 1 if (args.strict and not res["ok"]) else 0
|
|
450
|
+
if args.cmd == "register":
|
|
451
|
+
l0, l1, sh = assemble_layers(args.repo, args.l0_text, args.l1_text, args.l0_file, args.l1_file, args.include_map, args.include_decisions, args.allow_external, redact=False)
|
|
452
|
+
print(json.dumps(register_prefix(args.repo, args.name, l0, l1, sh, args.provider, args.model, args.ttl, args.external_cache_id, args.strict), indent=2, ensure_ascii=False))
|
|
453
|
+
elif args.cmd == "build-payload":
|
|
454
|
+
repo_arg = args.repo or args.repo_pos
|
|
455
|
+
if args.name and not repo_arg:
|
|
456
|
+
raise SystemExit("--name requires <repo> or --repo so the registered snapshot can be loaded.")
|
|
457
|
+
l0, l1 = args.l0_text, args.l1_text
|
|
458
|
+
stale_sources: List[str] = []
|
|
459
|
+
if repo_arg and args.name:
|
|
460
|
+
sp = _snapshot_path(repo_arg, args.name)
|
|
461
|
+
if not sp.is_file():
|
|
462
|
+
raise SystemExit(f"Prefix snapshot not found for '{args.name}'. Run `register` first.")
|
|
463
|
+
snap = json.loads(sp.read_text(encoding="utf-8"))
|
|
464
|
+
l0, l1 = l0 or snap.get("l0_static", ""), l1 or snap.get("l1_project", "")
|
|
465
|
+
reg = load_registry(repo_arg)
|
|
466
|
+
if args.name in reg.get("prefixes", {}):
|
|
467
|
+
stale_sources = _stale_sources_for_entry(repo_arg, reg["prefixes"][args.name])
|
|
468
|
+
vol_parts = ([args.volatile_text] if args.volatile_text else []) + [read_safe_source(repo_arg, vf, allow_external=args.allow_external)[1] for vf in args.volatile_file]
|
|
469
|
+
out = build_provider_payload(l0, l1, "\n\n".join(p for p in vol_parts if p), args.user_task, args.provider, args.model, args.ttl, args.retention, args.strict)
|
|
470
|
+
if stale_sources:
|
|
471
|
+
out["stale_sources"] = stale_sources
|
|
472
|
+
print(json.dumps(out, indent=2, ensure_ascii=False))
|
|
473
|
+
elif args.cmd == "record-usage":
|
|
474
|
+
print(json.dumps(record_usage(args.repo, args.name, args.provider, args.model, json.loads(args.usage_json), args.tier, args.ttl, args.external_cache_id, args.input_price_per_1m), indent=2, ensure_ascii=False))
|
|
475
|
+
elif args.cmd == "status":
|
|
476
|
+
print(json.dumps(cache_status(args.repo, name=args.name), indent=2, ensure_ascii=False))
|
|
477
|
+
elif args.cmd == "diff":
|
|
478
|
+
sp = _snapshot_path(args.repo, args.name)
|
|
479
|
+
if not sp.is_file():
|
|
480
|
+
raise SystemExit(f"No registered snapshot found for '{args.name}'.")
|
|
481
|
+
old_snap = json.loads(sp.read_text(encoding="utf-8"))
|
|
482
|
+
l0, l1, _ = assemble_layers(args.repo, args.l0_text, args.l1_text, args.l0_file, args.l1_file, args.include_map, args.include_decisions, args.allow_external, redact=True)
|
|
483
|
+
print(json.dumps(diff_prefixes(old_snap.get("l0_static", ""), old_snap.get("l1_project", ""), l0, l1), indent=2, ensure_ascii=False))
|
|
484
|
+
return 0
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
if __name__ == "__main__":
|
|
488
|
+
raise SystemExit(main())
|
agent_efficiency/cli.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Console script entrypoint for `ae` / `agent-efficiency`."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from typing import Optional, Sequence
|
|
7
|
+
|
|
8
|
+
from agent_efficiency import bundle_root
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
12
|
+
root = bundle_root()
|
|
13
|
+
scripts_dir = str(root / "scripts")
|
|
14
|
+
if scripts_dir not in sys.path:
|
|
15
|
+
sys.path.insert(0, scripts_dir)
|
|
16
|
+
if not os.getenv("AGENT_EFFICIENCY_SKILLS_DIR"):
|
|
17
|
+
os.environ["AGENT_EFFICIENCY_SKILLS_DIR"] = str(root / "skills")
|
|
18
|
+
import ae_cli # type: ignore[import-not-found]
|
|
19
|
+
return int(ae_cli.main(argv))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
if __name__ == "__main__":
|
|
23
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Console script entrypoint for `ae-mcp` (defaults to lean 7-tool `--profile core`)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from typing import Optional, Sequence
|
|
7
|
+
|
|
8
|
+
from agent_efficiency import bundle_root
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
12
|
+
root = bundle_root()
|
|
13
|
+
mcp_dir = str(root / "mcp")
|
|
14
|
+
if mcp_dir not in sys.path:
|
|
15
|
+
sys.path.insert(0, mcp_dir)
|
|
16
|
+
if not os.getenv("AGENT_EFFICIENCY_SKILLS_DIR"):
|
|
17
|
+
os.environ["AGENT_EFFICIENCY_SKILLS_DIR"] = str(root / "skills")
|
|
18
|
+
if not os.getenv("AGENT_EFFICIENCY_MCP_PROFILE"):
|
|
19
|
+
os.environ["AGENT_EFFICIENCY_MCP_PROFILE"] = "core"
|
|
20
|
+
import server # type: ignore[import-not-found]
|
|
21
|
+
return int(server.main(list(argv) if argv is not None else None))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
if __name__ == "__main__":
|
|
25
|
+
raise SystemExit(main())
|