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,278 @@
1
+ """Prefix linting, line-level invalidation diffing, layer assembly & provider-native payload builders."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+ import stat
7
+ from pathlib import Path
8
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
9
+
10
+ from _ae_core import (
11
+ canonicalize_text,
12
+ compute_prefix_id,
13
+ detect_provider,
14
+ estimate_tokens,
15
+ find_secret_leak_lines,
16
+ frame_untrusted_data,
17
+ is_secret_path,
18
+ is_within,
19
+ min_cache_tokens_for_model,
20
+ redact_secrets,
21
+ sha256_text,
22
+ )
23
+
24
+ MAX_SOURCE_FILE_BYTES = 1_500_000
25
+
26
+ CACHE_BUSTER_PATTERNS: Tuple[Tuple[str, str, re.Pattern[str], str], ...] = (
27
+ (
28
+ "timestamp", "high",
29
+ re.compile(r"(?:\b20\d{2}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2})?(?:Z|[+-]\d{2}:?\d{2})?\b|(?i:\b(?:current\s+time|updated\s+at|generated\s+at|timestamp)\s*[:=]))"),
30
+ "Move wall-clock timestamps out of L0/L1 into L2 volatile context or external logs.",
31
+ ),
32
+ (
33
+ "uuid_or_nonce", "high",
34
+ re.compile(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"),
35
+ "Remove per-request UUIDs/nonces from stable prefix layers.",
36
+ ),
37
+ (
38
+ "volatile_counter", "medium",
39
+ re.compile(r"(?i)\b(?:turn|iteration|attempt|retry)\s*(?:#|:)?\s*\d+\b(?!\s+times\b)"),
40
+ "Move turn/attempt counters to L2 volatile context so prefix stays identical across turns.",
41
+ ),
42
+ (
43
+ "ephemeral_path", "medium",
44
+ re.compile(r"(?:/tmp/|/var/folders/|/private/var/folders/)[^\s\"']+"),
45
+ "Replace ephemeral temporary paths with repo-relative paths in stable prefixes.",
46
+ ),
47
+ (
48
+ "dynamic_state_include", "high",
49
+ re.compile(
50
+ r"(?:(?:^|[\s(])@(?:[^\s)]*\.agent-state/[^\s)]+|[^\s)]*(?:CHECKPOINT|HANDOFF|CURRENT_STATE|TASK_QUEUE|MEMORY)\.md\b)"
51
+ r"|(?im:^\s*(?:include|import|source)\s*[:=]\s*[^\n]*(?:\.agent-state/|(?:CHECKPOINT|HANDOFF|CURRENT_STATE|TASK_QUEUE)\.md\b)))"
52
+ ),
53
+ "Never include mutable .agent-state/* or CHECKPOINT.md/HANDOFF.md in L0/L1 prefixes; load on demand in L2 via `ae brief`.",
54
+ ),
55
+ )
56
+
57
+
58
+ def _check_unsorted_json_blocks(text: str) -> List[str]:
59
+ issues: List[str] = []
60
+ for m in re.finditer(r"```json\s*\n([\s\S]*?)```", text):
61
+ try:
62
+ obj = json.loads(m.group(1).strip())
63
+ except Exception:
64
+ continue
65
+ if isinstance(obj, dict) and len(obj) > 1:
66
+ keys = list(obj.keys())
67
+ if keys != sorted(keys):
68
+ issues.append(f"Unsorted JSON keys ({', '.join(keys[:4])}...) — serialize with sort_keys=True.")
69
+ return issues
70
+
71
+
72
+ def lint_prefix(l0_static: str, l1_project: str = "", provider: Optional[str] = None, model: str = "") -> Dict[str, Any]:
73
+ prov = detect_provider(model, provider)
74
+ min_tokens = min_cache_tokens_for_model(prov, model)
75
+
76
+ issues: List[Dict[str, Any]] = []
77
+ for layer_name, text in (("L0_STATIC", l0_static), ("L1_PROJECT", l1_project)):
78
+ if not text:
79
+ continue
80
+ for ln_no, line in enumerate(text.splitlines(), start=1):
81
+ for kind, severity, pattern, fix in CACHE_BUSTER_PATTERNS:
82
+ m = pattern.search(line)
83
+ if m:
84
+ issues.append({"layer": layer_name, "line": ln_no, "kind": kind, "severity": severity, "match": m.group(0)[:60], "fix": fix})
85
+ # 100% parity secret-leak detection using authoritative `_ae_core.security` patterns
86
+ for sec_ln in find_secret_leak_lines(text):
87
+ issues.append({
88
+ "layer": layer_name, "line": sec_ln, "kind": "secret_leak", "severity": "critical",
89
+ "match": "[REDACTED]", "fix": "Strip secrets immediately before storing or sending prompt prefixes.",
90
+ })
91
+ for jmsg in _check_unsorted_json_blocks(text):
92
+ issues.append({"layer": layer_name, "line": 0, "kind": "unsorted_json", "severity": "low", "match": "json block", "fix": jmsg})
93
+
94
+ l0_tok, l1_tok = estimate_tokens(l0_static), estimate_tokens(l1_project)
95
+ combined_tok = l0_tok + l1_tok
96
+ meets_threshold = combined_tok >= min_tokens
97
+ if not meets_threshold:
98
+ issues.append({"layer": "COMBINED", "line": 0, "kind": "below_min_cacheable_tokens", "severity": "info", "match": f"{combined_tok} < {min_tokens}", "fix": f"Prefix is ~{combined_tok} tok; {prov} ({model or 'default'}) caching activates at >={min_tokens} tok."})
99
+
100
+ blocking = [i for i in issues if i["severity"] in ("critical", "high")]
101
+ return {
102
+ "ok": len(blocking) == 0, "cacheable": len(blocking) == 0 and meets_threshold,
103
+ "provider": prov, "min_threshold_tokens": min_tokens,
104
+ "l0_tokens_est": l0_tok, "l1_tokens_est": l1_tok, "combined_tokens_est": combined_tok,
105
+ "issue_count": len(issues), "blocking_count": len(blocking), "issues": issues,
106
+ }
107
+
108
+
109
+ def diff_prefixes(old_l0: str, old_l1: str, new_l0: str, new_l1: str) -> Dict[str, Any]:
110
+ for layer_name, old_t, new_t in (("L0_STATIC", old_l0, new_l0), ("L1_PROJECT", old_l1, new_l1)):
111
+ if old_t == new_t:
112
+ continue
113
+ old_lines, new_lines = old_t.splitlines(), new_t.splitlines()
114
+ first_diff, shared_chars = 1, 0
115
+ for idx in range(min(len(old_lines), len(new_lines))):
116
+ if old_lines[idx] != new_lines[idx]:
117
+ first_diff = idx + 1
118
+ break
119
+ shared_chars += len(old_lines[idx]) + 1
120
+ else:
121
+ first_diff = min(len(old_lines), len(new_lines)) + 1
122
+ if layer_name == "L1_PROJECT":
123
+ shared_chars += len(old_l0)
124
+ old_tok = estimate_tokens(old_l0 + old_l1)
125
+ pres_tok = estimate_tokens("x" * shared_chars)
126
+ return {
127
+ "cache_intact": False, "diverged_layer": layer_name, "first_diverging_line": first_diff,
128
+ "old_line": old_lines[first_diff - 1][:160] if first_diff - 1 < len(old_lines) else "<EOF>",
129
+ "new_line": new_lines[first_diff - 1][:160] if first_diff - 1 < len(new_lines) else "<EOF>",
130
+ "preserved_prefix_tokens_est": pres_tok, "invalidated_tokens_est": max(0, old_tok - pres_tok),
131
+ }
132
+ return {"cache_intact": True, "diverged_layer": None, "first_diverging_line": None, "preserved_prefix_tokens_est": estimate_tokens(new_l0 + new_l1), "invalidated_tokens_est": 0}
133
+
134
+
135
+ def read_safe_source(repo: Optional[Path], raw_fp: str, allow_external: bool = False) -> Tuple[str, str]:
136
+ if repo is not None:
137
+ repo_r = repo.resolve()
138
+ cand = Path(raw_fp)
139
+ full = cand.resolve() if cand.is_absolute() else (repo_r / cand).resolve()
140
+ try:
141
+ rel = full.relative_to(repo_r).as_posix()
142
+ except ValueError:
143
+ if not allow_external:
144
+ raise SystemExit(f"Source file escapes repository root: {raw_fp} (pass --allow-external to override).")
145
+ rel = str(full)
146
+ else:
147
+ full = Path(raw_fp).resolve()
148
+ rel = str(full)
149
+ if is_secret_path(rel.replace("\\", "/")):
150
+ raise SystemExit(f"Refusing to read sensitive/secret file into prompt context: {rel}")
151
+ if not full.exists():
152
+ raise SystemExit(f"Source file not found: {raw_fp}")
153
+ st = full.stat()
154
+ if not stat.S_ISREG(st.st_mode) or st.st_size > MAX_SOURCE_FILE_BYTES:
155
+ raise SystemExit(f"Non-regular or oversized source file: {raw_fp}")
156
+ return rel, full.read_text(encoding="utf-8", errors="replace")
157
+
158
+
159
+ def assemble_layers(
160
+ repo: Optional[Path],
161
+ l0_text: str = "",
162
+ l1_text: str = "",
163
+ l0_files: Sequence[str] = (),
164
+ l1_files: Sequence[str] = (),
165
+ include_map: bool = False,
166
+ include_decisions: bool = False,
167
+ allow_external: bool = False,
168
+ redact: bool = True,
169
+ ) -> Tuple[str, str, Dict[str, str]]:
170
+ source_hashes: Dict[str, str] = {}
171
+ l0_parts: List[str] = []
172
+ l1_parts: List[str] = []
173
+ maybe = redact_secrets if redact else (lambda s: s)
174
+
175
+ if l0_text:
176
+ l0_parts.append(canonicalize_text(maybe(l0_text)))
177
+ for fp in l0_files:
178
+ rel, raw = read_safe_source(repo, fp, allow_external=allow_external)
179
+ source_hashes[rel] = sha256_text(raw)[:16]
180
+ l0_parts.append(f"<!-- source: {rel} -->\n" + canonicalize_text(maybe(raw)))
181
+
182
+ if include_map and repo:
183
+ mp = repo.resolve() / ".agent-index" / "PROJECT_MAP.md"
184
+ if mp.is_file() and not mp.is_symlink() and is_within(mp, repo):
185
+ raw = mp.read_text(encoding="utf-8", errors="replace")
186
+ source_hashes[".agent-index/PROJECT_MAP.md"] = sha256_text(raw)[:16]
187
+ l1_parts.append(canonicalize_text(maybe(raw)))
188
+
189
+ if include_decisions and repo:
190
+ dp = repo.resolve() / ".agent-state" / "DECISIONS.md"
191
+ if dp.is_file() and not dp.is_symlink() and is_within(dp, repo):
192
+ active = dp.read_text(encoding="utf-8", errors="replace").split("## Superseded / Archived Decisions", 1)[0].strip()
193
+ source_hashes[".agent-state/DECISIONS.md"] = sha256_text(active)[:16]
194
+ l1_parts.append(canonicalize_text(maybe(active)))
195
+
196
+ if l1_text:
197
+ l1_parts.append(canonicalize_text(maybe(l1_text)))
198
+ for fp in l1_files:
199
+ rel, raw = read_safe_source(repo, fp, allow_external=allow_external)
200
+ source_hashes[rel] = sha256_text(raw)[:16]
201
+ l1_parts.append(f"<!-- source: {rel} -->\n" + canonicalize_text(maybe(raw)))
202
+
203
+ return canonicalize_text("\n".join(p for p in l0_parts if p)), canonicalize_text("\n".join(p for p in l1_parts if p)), source_hashes
204
+
205
+
206
+ def build_provider_payload(
207
+ l0_static: str,
208
+ l1_project: str,
209
+ l2_volatile: str,
210
+ user_task: str,
211
+ provider: Optional[str] = None,
212
+ model: str = "",
213
+ ttl: str = "5m",
214
+ retention: str = "in_memory",
215
+ strict: bool = False,
216
+ ) -> Dict[str, Any]:
217
+ raw_l0, raw_l1 = canonicalize_text(l0_static), canonicalize_text(l1_project)
218
+ prov = detect_provider(model, provider)
219
+ lint = lint_prefix(raw_l0, raw_l1, provider=prov, model=model)
220
+ if strict and not lint["ok"]:
221
+ raise SystemExit(f"Payload prefix failed strict cache-buster lint: {json.dumps(lint['issues'], indent=2)}")
222
+
223
+ l0, l1 = canonicalize_text(redact_secrets(raw_l0)), canonicalize_text(redact_secrets(raw_l1))
224
+ prefix_id, _ = compute_prefix_id(l0, l1)
225
+ l1_framed = frame_untrusted_data("L1_PROJECT", l1) if l1 else ""
226
+ l2_clean = redact_secrets(l2_volatile.strip())
227
+ l2_framed = frame_untrusted_data("L2_VOLATILE", l2_clean).strip() if l2_clean else ""
228
+ combined_user = "\n\n".join(p for p in (l2_framed, redact_secrets(user_task.strip())) if p)
229
+
230
+ if prov == "anthropic":
231
+ cc: Dict[str, Any] = {"type": "ephemeral", **({"ttl": "1h"} if ttl == "1h" else {})}
232
+ sys_b = ([{"type": "text", "text": l0, "cache_control": dict(cc)}] if l0 else []) + ([{"type": "text", "text": l1_framed, "cache_control": dict(cc)}] if l1_framed else [])
233
+ payload: Dict[str, Any] = {"system": sys_b, "messages": [{"role": "user", "content": combined_user}]}
234
+ elif prov == "openai":
235
+ pfx = "\n\n".join(p for p in (l0, l1_framed) if p)
236
+ msgs = ([{"role": "developer", "content": pfx}] if pfx else []) + [{"role": "user", "content": combined_user}]
237
+ payload = {"messages": msgs, "prompt_cache_key": prefix_id, "prompt_cache_retention": retention}
238
+ elif prov == "gemini":
239
+ pfx = "\n\n".join(p for p in (l0, l1_framed) if p)
240
+ payload = {
241
+ "contents": [{"role": "user", "parts": [{"text": combined_user}]}],
242
+ "explicit_cached_content_spec": {"display_name": prefix_id, "ttl": "3600s" if ttl == "1h" else "300s", "system_instruction": {"parts": [{"text": pfx}]}},
243
+ }
244
+ if pfx:
245
+ payload["system_instruction"] = {"parts": [{"text": pfx}]}
246
+ elif prov == "bedrock":
247
+ sys_b = []
248
+ if l0:
249
+ sys_b.extend([{"text": l0}, {"cachePoint": {"type": "default"}}])
250
+ if l1_framed:
251
+ sys_b.extend([{"text": l1_framed}, {"cachePoint": {"type": "default"}}])
252
+ payload = {"system": sys_b, "messages": [{"role": "user", "content": [{"text": combined_user}]}]}
253
+ else:
254
+ inferred = detect_provider(model, None, default_when_empty="litellm")
255
+ use_cc = inferred in ("anthropic", "bedrock")
256
+ msgs = []
257
+ extra: Dict[str, Any] = {}
258
+ if use_cc:
259
+ cc = {"type": "ephemeral", **({"ttl": "1h"} if ttl == "1h" and inferred != "bedrock" else {})}
260
+ sb = ([{"type": "text", "text": l0, "cache_control": dict(cc)}] if l0 else []) + ([{"type": "text", "text": l1_framed, "cache_control": dict(cc)}] if l1_framed else [])
261
+ if sb:
262
+ msgs.append({"role": "system", "content": sb})
263
+ else:
264
+ pfx = "\n\n".join(p for p in (l0, l1_framed) if p)
265
+ if pfx:
266
+ msgs.append({"role": "system", "content": pfx})
267
+ if inferred == "openai":
268
+ extra["prompt_cache_key"] = prefix_id
269
+ msgs.append({"role": "user", "content": combined_user})
270
+ payload = {"messages": msgs, "extra_params": extra}
271
+
272
+ return {
273
+ "provider": prov, "model": model or None, "prefix_id": prefix_id,
274
+ "l0_tokens_est": estimate_tokens(l0), "l1_tokens_est": estimate_tokens(l1),
275
+ "l2_tokens_est": estimate_tokens(combined_user),
276
+ "cacheable_prefix_tokens_est": estimate_tokens(l0) + estimate_tokens(l1),
277
+ "lint": lint, "payload": payload,
278
+ }