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,219 @@
|
|
|
1
|
+
"""Monorepo & workspace import-alias discovery (tsconfig paths, package.json workspaces, go.mod module paths)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import posixpath
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict, List, Optional, Set, Tuple
|
|
9
|
+
|
|
10
|
+
from _ae_core import is_within
|
|
11
|
+
|
|
12
|
+
_TS_EXTS = ("", ".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", "/index.ts", "/index.tsx", "/index.js", "/index.jsx")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _strip_jsonc(raw: str) -> str:
|
|
16
|
+
"""Strip // and /* */ comments and trailing commas from tsconfig.json/jsconfig.json without external deps."""
|
|
17
|
+
out: List[str] = []
|
|
18
|
+
i, n = 0, len(raw)
|
|
19
|
+
in_str = False
|
|
20
|
+
while i < n:
|
|
21
|
+
ch = raw[i]
|
|
22
|
+
nxt = raw[i + 1] if i + 1 < n else ""
|
|
23
|
+
if in_str:
|
|
24
|
+
out.append(ch)
|
|
25
|
+
if ch == "\\" and i + 1 < n:
|
|
26
|
+
out.append(nxt)
|
|
27
|
+
i += 2
|
|
28
|
+
continue
|
|
29
|
+
if ch == '"':
|
|
30
|
+
in_str = False
|
|
31
|
+
i += 1
|
|
32
|
+
continue
|
|
33
|
+
if ch == '"':
|
|
34
|
+
in_str = True
|
|
35
|
+
out.append(ch)
|
|
36
|
+
i += 1
|
|
37
|
+
continue
|
|
38
|
+
if ch == "/" and nxt == "/":
|
|
39
|
+
i += 2
|
|
40
|
+
while i < n and raw[i] != "\n":
|
|
41
|
+
i += 1
|
|
42
|
+
continue
|
|
43
|
+
if ch == "/" and nxt == "*":
|
|
44
|
+
i += 2
|
|
45
|
+
while i + 1 < n and not (raw[i] == "*" and raw[i + 1] == "/"):
|
|
46
|
+
i += 1
|
|
47
|
+
i += 2
|
|
48
|
+
continue
|
|
49
|
+
out.append(ch)
|
|
50
|
+
i += 1
|
|
51
|
+
cleaned = "".join(out)
|
|
52
|
+
return re.sub(r",\s*([}\]])", r"\1", cleaned)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _safe_load_jsonc(path: Path, repo: Path) -> Optional[Dict[str, Any]]:
|
|
56
|
+
if path.is_symlink() or not path.is_file() or not is_within(path, repo):
|
|
57
|
+
return None
|
|
58
|
+
try:
|
|
59
|
+
data = json.loads(_strip_jsonc(path.read_text(encoding="utf-8", errors="replace")))
|
|
60
|
+
return data if isinstance(data, dict) else None
|
|
61
|
+
except Exception:
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def load_workspace_aliases(repo: Path, indexed_paths: Set[str]) -> Dict[str, Any]:
|
|
66
|
+
"""Discover TS path aliases, npm/pnpm workspace packages, and Go module prefixes from indexed files."""
|
|
67
|
+
repo_r = repo.resolve()
|
|
68
|
+
ts_aliases: List[Tuple[str, str, List[str]]] = [] # (config_dir, pattern, targets)
|
|
69
|
+
ts_base_urls: Dict[str, str] = {}
|
|
70
|
+
pkg_entries: Dict[str, str] = {} # package_name -> repo-relative entry path or dir
|
|
71
|
+
go_modules: List[Tuple[str, str]] = [] # (module_prefix, mod_dir)
|
|
72
|
+
|
|
73
|
+
for rel in sorted(indexed_paths):
|
|
74
|
+
name = Path(rel).name.lower()
|
|
75
|
+
rel_dir = "" if "/" not in rel else rel.rsplit("/", 1)[0]
|
|
76
|
+
|
|
77
|
+
if name in ("tsconfig.json", "tsconfig.base.json", "jsconfig.json"):
|
|
78
|
+
cfg = _safe_load_jsonc(repo_r / rel, repo_r)
|
|
79
|
+
if cfg:
|
|
80
|
+
co = cfg.get("compilerOptions") or {}
|
|
81
|
+
if isinstance(co, dict):
|
|
82
|
+
base_url = str(co.get("baseUrl") or ".").strip()
|
|
83
|
+
resolved_base = posixpath.normpath(posixpath.join(rel_dir, base_url)) if rel_dir else posixpath.normpath(base_url)
|
|
84
|
+
if resolved_base == ".":
|
|
85
|
+
resolved_base = ""
|
|
86
|
+
ts_base_urls[rel_dir] = resolved_base
|
|
87
|
+
paths = co.get("paths") or {}
|
|
88
|
+
if isinstance(paths, dict):
|
|
89
|
+
for pat, tgts in paths.items():
|
|
90
|
+
if isinstance(tgts, list):
|
|
91
|
+
str_tgts = [str(t) for t in tgts if isinstance(t, str)]
|
|
92
|
+
if str_tgts:
|
|
93
|
+
ts_aliases.append((resolved_base, str(pat), str_tgts))
|
|
94
|
+
|
|
95
|
+
elif name == "package.json":
|
|
96
|
+
pkg = _safe_load_jsonc(repo_r / rel, repo_r)
|
|
97
|
+
if pkg and isinstance(pkg.get("name"), str) and pkg["name"].strip():
|
|
98
|
+
pname = pkg["name"].strip()
|
|
99
|
+
# Determine main entry point relative to package dir
|
|
100
|
+
candidates: List[str] = []
|
|
101
|
+
for key in ("types", "module", "main"):
|
|
102
|
+
if isinstance(pkg.get(key), str):
|
|
103
|
+
candidates.append(pkg[key])
|
|
104
|
+
exports = pkg.get("exports")
|
|
105
|
+
if isinstance(exports, str):
|
|
106
|
+
candidates.append(exports)
|
|
107
|
+
elif isinstance(exports, dict):
|
|
108
|
+
dot = exports.get(".")
|
|
109
|
+
if isinstance(dot, str):
|
|
110
|
+
candidates.append(dot)
|
|
111
|
+
elif isinstance(dot, dict):
|
|
112
|
+
for subk in ("import", "default", "require", "types"):
|
|
113
|
+
if isinstance(dot.get(subk), str):
|
|
114
|
+
candidates.append(dot[subk])
|
|
115
|
+
candidates.extend(["src/index.ts", "src/index.tsx", "src/index.js", "index.ts", "index.js"])
|
|
116
|
+
chosen: Optional[str] = None
|
|
117
|
+
for cand in candidates:
|
|
118
|
+
joined = posixpath.normpath(posixpath.join(rel_dir, cand)) if rel_dir else posixpath.normpath(cand)
|
|
119
|
+
for ext in ("", ".ts", ".tsx", ".js", ".jsx"):
|
|
120
|
+
if (joined + ext) in indexed_paths:
|
|
121
|
+
chosen = joined + ext
|
|
122
|
+
break
|
|
123
|
+
if chosen:
|
|
124
|
+
break
|
|
125
|
+
pkg_entries[pname] = chosen or rel_dir
|
|
126
|
+
|
|
127
|
+
elif name == "go.mod":
|
|
128
|
+
fp = repo_r / rel
|
|
129
|
+
if not fp.is_symlink() and fp.is_file() and is_within(fp, repo_r):
|
|
130
|
+
try:
|
|
131
|
+
for line in fp.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
132
|
+
m = re.match(r"^\s*module\s+(\S+)", line)
|
|
133
|
+
if m:
|
|
134
|
+
go_modules.append((m.group(1).strip('"'), rel_dir))
|
|
135
|
+
break
|
|
136
|
+
except OSError:
|
|
137
|
+
pass
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
"ts_aliases": ts_aliases,
|
|
141
|
+
"ts_base_urls": ts_base_urls,
|
|
142
|
+
"pkg_entries": pkg_entries,
|
|
143
|
+
"go_modules": go_modules,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _match_ts_target(base_rel: str, all_paths: Set[str]) -> Optional[str]:
|
|
148
|
+
norm = posixpath.normpath(base_rel).lstrip("./")
|
|
149
|
+
for sfx in _TS_EXTS:
|
|
150
|
+
cand = norm + sfx
|
|
151
|
+
if cand in all_paths:
|
|
152
|
+
return cand
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def resolve_workspace_import(
|
|
157
|
+
src_path: str,
|
|
158
|
+
raw_target: str,
|
|
159
|
+
all_paths: Set[str],
|
|
160
|
+
ws: Optional[Dict[str, Any]],
|
|
161
|
+
) -> Optional[str]:
|
|
162
|
+
"""Resolve tsconfig path aliases, workspace package imports, and Go module imports."""
|
|
163
|
+
if not ws or not raw_target:
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
# 1. tsconfig / jsconfig path aliases (e.g. `@/components/Button` -> `src/components/Button.tsx`)
|
|
167
|
+
for base_dir, pat, targets in ws.get("ts_aliases", ()):
|
|
168
|
+
if "*" in pat:
|
|
169
|
+
prefix, suffix = pat.split("*", 1)
|
|
170
|
+
if raw_target.startswith(prefix) and raw_target.endswith(suffix):
|
|
171
|
+
mid = raw_target[len(prefix) : (len(raw_target) - len(suffix) if suffix else len(raw_target))]
|
|
172
|
+
for t in targets:
|
|
173
|
+
replaced = t.replace("*", mid)
|
|
174
|
+
joined = posixpath.join(base_dir, replaced) if base_dir else replaced
|
|
175
|
+
hit = _match_ts_target(joined, all_paths)
|
|
176
|
+
if hit:
|
|
177
|
+
return hit
|
|
178
|
+
elif raw_target == pat:
|
|
179
|
+
for t in targets:
|
|
180
|
+
joined = posixpath.join(base_dir, t) if base_dir else t
|
|
181
|
+
hit = _match_ts_target(joined, all_paths)
|
|
182
|
+
if hit:
|
|
183
|
+
return hit
|
|
184
|
+
|
|
185
|
+
# 2. Monorepo package.json workspace imports (`@acme/shared` or `@acme/shared/utils`)
|
|
186
|
+
pkg_entries: Dict[str, str] = ws.get("pkg_entries", {})
|
|
187
|
+
if raw_target in pkg_entries:
|
|
188
|
+
entry = pkg_entries[raw_target]
|
|
189
|
+
if entry in all_paths:
|
|
190
|
+
return entry
|
|
191
|
+
hit = _match_ts_target(entry, all_paths)
|
|
192
|
+
if hit:
|
|
193
|
+
return hit
|
|
194
|
+
for pname, entry in pkg_entries.items():
|
|
195
|
+
if raw_target.startswith(pname + "/"):
|
|
196
|
+
sub = raw_target[len(pname) + 1 :]
|
|
197
|
+
pkg_dir = entry.rsplit("/", 1)[0] if entry in all_paths and "/" in entry else entry
|
|
198
|
+
# Try both package root and package/src
|
|
199
|
+
for base_try in (posixpath.join(pkg_dir, sub), posixpath.join(pkg_dir, "src", sub)):
|
|
200
|
+
hit = _match_ts_target(base_try, all_paths)
|
|
201
|
+
if hit:
|
|
202
|
+
return hit
|
|
203
|
+
|
|
204
|
+
# 3. Go module imports (`github.com/acme/proj/internal/auth` -> first .go file in `internal/auth/`)
|
|
205
|
+
if src_path.endswith(".go"):
|
|
206
|
+
for mod_prefix, mod_dir in ws.get("go_modules", ()):
|
|
207
|
+
if raw_target == mod_prefix or raw_target.startswith(mod_prefix + "/"):
|
|
208
|
+
sub = raw_target[len(mod_prefix) :].lstrip("/")
|
|
209
|
+
target_dir = posixpath.normpath(posixpath.join(mod_dir, sub)) if mod_dir else sub
|
|
210
|
+
prefix = (target_dir + "/") if target_dir and target_dir != "." else ""
|
|
211
|
+
go_files = sorted(
|
|
212
|
+
p for p in all_paths
|
|
213
|
+
if p.endswith(".go") and not p.endswith("_test.go") and p != src_path
|
|
214
|
+
and ((not prefix and "/" not in p) or (prefix and p.startswith(prefix) and "/" not in p[len(prefix) :]))
|
|
215
|
+
)
|
|
216
|
+
if go_files:
|
|
217
|
+
return go_files[0]
|
|
218
|
+
|
|
219
|
+
return None
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: prompt-cache-manager
|
|
3
|
+
description: Use when building custom LLM API pipelines (skip for standard IDE chat) to lint L0/L1 prompt prefixes for cache-busters or secret leaks, build provider cache payloads, and verify provider cache telemetry.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Prompt Cache Manager
|
|
7
|
+
|
|
8
|
+
Keep stable context byte-identical at the front of every prompt, lint out cache-busters and secrets before calling a provider, wire provider-native cache parameters, and remember warm prefixes plus verified telemetry in `<repo>/.agent-state/cache_registry.json`. Invoke via `python3 <skill-dir>/scripts/prompt_cache.py`.
|
|
9
|
+
|
|
10
|
+
## Target Runtime Guidance
|
|
11
|
+
|
|
12
|
+
- **Custom LLM pipelines / SDK orchestrators:** Use the full loop (`register` → `build-payload` → provider API call → `record-usage` with real provider response JSON).
|
|
13
|
+
- **Interactive IDE/CLI coding agents (Antigravity, Claude Code, Codex, Cursor):** Your host runtime constructs API payloads and manages provider caching automatically. Use `ae doctor` or `prompt_cache.py lint` / `diff` when auditing repo prompt files (`CLAUDE.md`, `AGENTS.md`, `PROJECT_MAP.md`, `DECISIONS.md`) for cache-busters or secret leaks, and **do not** run `build-payload` or fabricate `record-usage` numbers during ordinary coding turns.
|
|
14
|
+
|
|
15
|
+
## 3-Layer Prompt Architecture (Strict Order)
|
|
16
|
+
|
|
17
|
+
1. **`L0_STATIC` (Frozen)**: System instructions, safety/coding rules, tool schemas, project constitution (`--l0-file AGENTS.md` or inline `--l0-text`). Changes rarely.
|
|
18
|
+
2. **`L1_PROJECT` (Semi-Stable)**: Deterministic `.agent-index/PROJECT_MAP.md` (`--include-map`, metadata placed at bottom so single-file edits preserve top sections) + active `.agent-state/DECISIONS.md` (`--include-decisions`). Pinned in `.agent-state/cache/snapshots/` until re-registered.
|
|
19
|
+
3. **`L2_VOLATILE` (Per-Turn, User Role Only)**: `HANDOFF.md`, targeted code slices, git diffs, trace metadata (timestamps, turn/request IDs), user prompt. **Always placed strictly after L0/L1, never in `role: "system"`.**
|
|
20
|
+
|
|
21
|
+
## Required Workflow (LLM Pipelines & Audits)
|
|
22
|
+
|
|
23
|
+
1. **Check existing warm prefixes first**:
|
|
24
|
+
```bash
|
|
25
|
+
python3 <skill-dir>/scripts/prompt_cache.py status <repo>
|
|
26
|
+
python3 <skill-dir>/scripts/prompt_cache.py diff <repo> --name core --l0-file AGENTS.md --include-map --include-decisions
|
|
27
|
+
```
|
|
28
|
+
2. **Register & strictly lint a reusable prefix** (lints BEFORE redacting with full `_ae_core.security` parity; auto-infers provider & model-specific token threshold):
|
|
29
|
+
```bash
|
|
30
|
+
python3 <skill-dir>/scripts/prompt_cache.py register <repo> --name core \
|
|
31
|
+
--l0-file AGENTS.md --include-map --include-decisions --model claude-sonnet-4-5 --strict
|
|
32
|
+
```
|
|
33
|
+
3. **Build provider-native cached payload** (`anthropic`, `openai`, `gemini`, `bedrock`, `litellm`; accepts positional `<repo>` or `--repo <repo>`; flags `stale_sources` if source files drifted):
|
|
34
|
+
```bash
|
|
35
|
+
python3 <skill-dir>/scripts/prompt_cache.py build-payload <repo> --name core \
|
|
36
|
+
--volatile-text "trace: turn=1" --user-task "Investigate auth refresh root cause" --model claude-sonnet-4-5
|
|
37
|
+
```
|
|
38
|
+
*(Add `--volatile-file .agent-state/HANDOFF.md` when resuming a prepared handoff.)*
|
|
39
|
+
4. **Record verified provider usage metadata** (supports Anthropic, OpenAI Chat & Responses API `input_tokens_details`, Gemini SDK & REST camelCase, Bedrock):
|
|
40
|
+
```bash
|
|
41
|
+
python3 <skill-dir>/scripts/prompt_cache.py record-usage <repo> --name core \
|
|
42
|
+
--model claude-sonnet-4-5 --tier medium \
|
|
43
|
+
--usage-json '{"input_tokens":400,"cache_read_input_tokens":3200,"output_tokens":350}'
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Cache-Buster & Threshold Guardrails
|
|
47
|
+
|
|
48
|
+
- **Never put in `L0_STATIC` or `L1_PROJECT`**: wall-clock timestamps, UUIDs/trace IDs, turn/attempt counters (`Turn 4`), temp paths (`/tmp/...`), unsorted JSON keys, or mutating diffs.
|
|
49
|
+
- **Model-specific activation thresholds**: OpenAI & Anthropic Sonnet = **≥1,024 tokens**; legacy Anthropic Haiku / Gemini Pro = **≥2,048 tokens**; **Claude Haiku 4.5 & Claude Opus 4.5/4.6 = ≥4,096 tokens**. Check `lint.cacheable` and `lint.min_threshold_tokens`.
|
|
50
|
+
- **Verification rule**: Never claim a cache hit from local prefix reuse alone or invent usage numbers. Confirm reads strictly from real provider response metadata via `record-usage`.
|
|
51
|
+
|
|
52
|
+
Provider breakpoint syntax, TTLs, and cache-affinity vs model-switching math: [references/provider-caching.md](references/provider-caching.md).
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# Provider Prompt Caching Reference
|
|
2
|
+
|
|
3
|
+
## Contents
|
|
4
|
+
- Provider Matrix
|
|
5
|
+
- Breakpoint & Prefix Rules
|
|
6
|
+
- Cache-Affinity vs Model-Switching Economics
|
|
7
|
+
- Diagnosing Cache Misses
|
|
8
|
+
- Registry Schema
|
|
9
|
+
|
|
10
|
+
## Provider Matrix
|
|
11
|
+
|
|
12
|
+
| Provider | Activation Mechanism | Min Prefix Threshold | Typical TTL | Typical Read Discount / Write Premium | Usage Metadata Fields |
|
|
13
|
+
|---|---|---|---|---|---|
|
|
14
|
+
| **Anthropic** | Explicit `cache_control: {"type": "ephemeral"}` (optional `"ttl": "1h"`) on up to 4 blocks | **1,024 tok** (Sonnet), **2,048 tok** (legacy Haiku), **4,096 tok** (Haiku 4.5, Opus 4.5/4.6) | 5 min (or 1h) | ~90% read discount; write **+25%** (5m) / **+100%** (1h) | `cache_read_input_tokens`, `cache_creation_input_tokens` |
|
|
15
|
+
| **OpenAI** | Automatic exact-prefix + `prompt_cache_key` routing + `prompt_cache_retention` (`in_memory` / `24h`) | 1,024 tok (128-tok increments) | 5–10 min (or 24h) | ~50%+ read discount (no write premium) | `prompt_tokens_details.cached_tokens` (Chat) or `input_tokens_details.cached_tokens` (Responses API) |
|
|
16
|
+
| **Gemini** | Implicit prefix caching (automatic) + Explicit `CachedContent` resource (`caches.create`) | 1,024 tok (Flash) / 2,048 tok (Pro) | Configurable (default 1h) | ~75% read discount (no write premium) | `cached_content_token_count`/`prompt_token_count` (SDK) or `cachedContentTokenCount`/`promptTokenCount` (REST) |
|
|
17
|
+
| **AWS Bedrock** | Explicit `{"cachePoint": {"type": "default"}}` blocks | 1,024–4,096 tok (model-dependent) | 5 min | ~90% read discount (+25% write) | `cacheReadInputTokens`, `cacheWriteInputTokens` |
|
|
18
|
+
|
|
19
|
+
## Breakpoint & Prefix Rules
|
|
20
|
+
|
|
21
|
+
1. **Prefix matching is byte-exact from token 0.** A single changed character in `L0_STATIC` invalidates BOTH `L0_STATIC` and `L1_PROJECT`.
|
|
22
|
+
2. **Keep tool definitions and `L0_STATIC` frozen.** Sort JSON tool schemas and config keys deterministically (`sort_keys=True`).
|
|
23
|
+
3. **Separate `L0` and `L1` breakpoints** on Anthropic/Bedrock so refreshing `L1_PROJECT` still preserves the cached `L0_STATIC` prefix.
|
|
24
|
+
4. **Never put global hashes or timestamps at the top of `PROJECT_MAP.md`.** `local-context-index` places `## Index Metadata` (totals + fingerprint) at the bottom of `PROJECT_MAP.md` to preserve upper sections.
|
|
25
|
+
5. **Preserve prefix across agent handoffs.** Store `prefix_id` and `name` in `.agent-state/cache_registry.json` so receiving agents on the same model tier hit the warm cache immediately.
|
|
26
|
+
|
|
27
|
+
## Cache-Affinity vs Model-Switching Economics
|
|
28
|
+
|
|
29
|
+
Switching models invalidates provider prompt caches (caches are scoped per provider + model + prefix).
|
|
30
|
+
|
|
31
|
+
- **Down-shifting** (e.g. `balanced` → `fast`) for a single turn while a large prefix is warm (e.g., 25,000 tokens within TTL at `$0.30/1M` cached vs `$1.00/1M` cold on `fast`) can **cost more** than staying on the warm `balanced` cache.
|
|
32
|
+
- **Rule**:
|
|
33
|
+
- **Up-shift immediately** on security, high risk, or repeated failures—correctness beats cache savings.
|
|
34
|
+
- **Down-shift cleanly** when (a) cache is cold/expired, (b) spawning an isolated subagent with a tiny fresh prompt, or (c) entering a multi-turn mechanical batch where amortizing the cold write saves money.
|
|
35
|
+
- `adaptive-orchestration-handoff`'s `route_task.py` reads `.agent-state/cache_registry.json` automatically to enforce this hysteresis.
|
|
36
|
+
|
|
37
|
+
## Diagnosing Cache Misses
|
|
38
|
+
|
|
39
|
+
Run `python3 scripts/prompt_cache.py diff <repo> --name <prefix> ...`:
|
|
40
|
+
1. `cache_intact: false` → Inspect `diverged_layer` and `first_diverging_line` to eliminate the volatile token.
|
|
41
|
+
2. `cache_intact: true` but `cache_read_tokens == 0`:
|
|
42
|
+
- Check `combined_tokens_est >= min_threshold_tokens` (note **4,096** minimum on Claude Haiku 4.5 and Opus 4.5/4.6!).
|
|
43
|
+
- Check `ttl_remaining_seconds > 0` in `status` (did the 5m window expire between turns?).
|
|
44
|
+
- Check whether the model ID or tool schema changed between turns.
|
|
45
|
+
- Verify the provider actually supports caching on the configured model ID.
|
|
46
|
+
|
|
47
|
+
## Registry Schema
|
|
48
|
+
|
|
49
|
+
Stored atomically in `<repo>/.agent-state/cache_registry.json`:
|
|
50
|
+
- `prefixes.<name>`: `prefix_id`, `l0_sha`, `l1_sha`, `combined_sha`, token estimates, `source_files` SHA-256 map, `sessions` map keyed by `<provider>:<model>` with `expires_at`, `external_cache_id`, hits/misses, and savings.
|
|
51
|
+
- `totals`: cumulative `calls`, `verified_cache_hits`, `cache_misses`, `input_tokens`, `cache_read_tokens`, `cache_write_tokens`, `output_tokens`, `estimated_savings_usd`.
|
|
52
|
+
- Redacted snapshots stored in `<repo>/.agent-state/cache/snapshots/<name>.json` for exact line-level `diff`.
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Shared zero-dependency core for AgentEfficiency skills (synced into each skill for standalone use)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from _ae_core.io_lock import (
|
|
5
|
+
atomic_write_json,
|
|
6
|
+
atomic_write_text,
|
|
7
|
+
canonicalize_text,
|
|
8
|
+
compute_prefix_id,
|
|
9
|
+
configure_utf8_stdio,
|
|
10
|
+
ensure_git_info_exclude,
|
|
11
|
+
estimate_tokens,
|
|
12
|
+
file_lock,
|
|
13
|
+
git_cmd,
|
|
14
|
+
sha256_text,
|
|
15
|
+
sources_fresh,
|
|
16
|
+
)
|
|
17
|
+
from _ae_core.security import (
|
|
18
|
+
HARD_SECRET_PATH_RE,
|
|
19
|
+
SECRET_CONTENT_PATTERNS,
|
|
20
|
+
SECRET_PATH_RE,
|
|
21
|
+
SOFT_SECRET_NAME_RE,
|
|
22
|
+
SOURCE_CODE_EXTS,
|
|
23
|
+
find_secret_leak_lines,
|
|
24
|
+
frame_untrusted_data,
|
|
25
|
+
has_secret_leak,
|
|
26
|
+
is_secret_path,
|
|
27
|
+
is_within,
|
|
28
|
+
normalize_rel_path,
|
|
29
|
+
redact_secrets,
|
|
30
|
+
redact_secrets_with_flag,
|
|
31
|
+
sanitize_inline,
|
|
32
|
+
)
|
|
33
|
+
from _ae_core.savings import (
|
|
34
|
+
DEFAULT_RATE_PER_1M_USD,
|
|
35
|
+
default_savings_path,
|
|
36
|
+
format_savings_card,
|
|
37
|
+
format_statusline,
|
|
38
|
+
record_saving,
|
|
39
|
+
summarize_savings,
|
|
40
|
+
)
|
|
41
|
+
from _ae_core.usage import (
|
|
42
|
+
ALIAS_TO_TIER,
|
|
43
|
+
DEFAULT_TIER_PRICES,
|
|
44
|
+
PROVIDER_DEFAULTS,
|
|
45
|
+
detect_provider,
|
|
46
|
+
min_cache_tokens_for_model,
|
|
47
|
+
parse_provider_usage,
|
|
48
|
+
usage_to_dict,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"ALIAS_TO_TIER",
|
|
53
|
+
"DEFAULT_RATE_PER_1M_USD",
|
|
54
|
+
"DEFAULT_TIER_PRICES",
|
|
55
|
+
"HARD_SECRET_PATH_RE",
|
|
56
|
+
"PROVIDER_DEFAULTS",
|
|
57
|
+
"SECRET_CONTENT_PATTERNS",
|
|
58
|
+
"SECRET_PATH_RE",
|
|
59
|
+
"SOFT_SECRET_NAME_RE",
|
|
60
|
+
"SOURCE_CODE_EXTS",
|
|
61
|
+
"atomic_write_json",
|
|
62
|
+
"atomic_write_text",
|
|
63
|
+
"canonicalize_text",
|
|
64
|
+
"compute_prefix_id",
|
|
65
|
+
"configure_utf8_stdio",
|
|
66
|
+
"default_savings_path",
|
|
67
|
+
"detect_provider",
|
|
68
|
+
"ensure_git_info_exclude",
|
|
69
|
+
"estimate_tokens",
|
|
70
|
+
"file_lock",
|
|
71
|
+
"find_secret_leak_lines",
|
|
72
|
+
"format_savings_card",
|
|
73
|
+
"format_statusline",
|
|
74
|
+
"frame_untrusted_data",
|
|
75
|
+
"git_cmd",
|
|
76
|
+
"has_secret_leak",
|
|
77
|
+
"is_secret_path",
|
|
78
|
+
"is_within",
|
|
79
|
+
"min_cache_tokens_for_model",
|
|
80
|
+
"normalize_rel_path",
|
|
81
|
+
"parse_provider_usage",
|
|
82
|
+
"record_saving",
|
|
83
|
+
"redact_secrets",
|
|
84
|
+
"redact_secrets_with_flag",
|
|
85
|
+
"sanitize_inline",
|
|
86
|
+
"sha256_text",
|
|
87
|
+
"sources_fresh",
|
|
88
|
+
"summarize_savings",
|
|
89
|
+
"usage_to_dict",
|
|
90
|
+
]
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Cross-platform POSIX (fcntl) + Windows (msvcrt) file locking, atomic IO, hashing & git helpers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import contextlib
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Dict, Iterator, Sequence, Tuple
|
|
15
|
+
|
|
16
|
+
from _ae_core.security import is_within
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
import fcntl
|
|
20
|
+
except ImportError: # pragma: no cover (Windows)
|
|
21
|
+
fcntl = None # type: ignore[assignment]
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
import msvcrt
|
|
25
|
+
except ImportError: # pragma: no cover (POSIX)
|
|
26
|
+
msvcrt = None # type: ignore[assignment]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def configure_utf8_stdio() -> None:
|
|
30
|
+
"""Reconfigure stdout/stderr to UTF-8 on Windows/narrow locales so Unicode CLI output never crashes."""
|
|
31
|
+
for stream in (sys.stdout, sys.stderr):
|
|
32
|
+
reconf = getattr(stream, "reconfigure", None)
|
|
33
|
+
if callable(reconf):
|
|
34
|
+
try:
|
|
35
|
+
reconf(encoding="utf-8", errors="replace")
|
|
36
|
+
except Exception:
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def estimate_tokens(text: str) -> int:
|
|
41
|
+
return max(1, (len(text) + 3) // 4) if text else 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def canonicalize_text(text: str) -> str:
|
|
45
|
+
if not text:
|
|
46
|
+
return ""
|
|
47
|
+
norm = text.replace("\r\n", "\n").replace("\r", "\n")
|
|
48
|
+
lines = [line.rstrip() for line in norm.split("\n")]
|
|
49
|
+
out = "\n".join(lines).strip()
|
|
50
|
+
out = re.sub(r"\n{3,}", "\n\n", out)
|
|
51
|
+
return (out + "\n") if out else ""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def sha256_text(text: str) -> str:
|
|
55
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def compute_prefix_id(l0: str, l1: str) -> Tuple[str, str]:
|
|
59
|
+
combined_sha = sha256_text(l0 + "\n---LAYER_BOUNDARY---\n" + l1)
|
|
60
|
+
return f"pfx-{combined_sha[:12]}", combined_sha
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _acquire_win_lock(fd: int, timeout_s: float = 10.0) -> None:
|
|
64
|
+
"""Acquire an exclusive byte-range lock on Windows via msvcrt.locking with bounded backoff."""
|
|
65
|
+
deadline = time.monotonic() + timeout_s
|
|
66
|
+
delay = 0.01
|
|
67
|
+
while True:
|
|
68
|
+
try:
|
|
69
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
70
|
+
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) # type: ignore[union-attr]
|
|
71
|
+
return
|
|
72
|
+
except OSError:
|
|
73
|
+
if time.monotonic() >= deadline:
|
|
74
|
+
raise TimeoutError(f"Timed out waiting for Windows file lock after {timeout_s}s")
|
|
75
|
+
time.sleep(delay)
|
|
76
|
+
delay = min(0.1, delay * 1.5)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _release_win_lock(fd: int) -> None:
|
|
80
|
+
try:
|
|
81
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
82
|
+
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) # type: ignore[union-attr]
|
|
83
|
+
except OSError:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@contextlib.contextmanager
|
|
88
|
+
def file_lock(lock_path: Path, timeout_s: float = 10.0) -> Iterator[None]:
|
|
89
|
+
"""Cross-platform exclusive file lock: fcntl.flock on POSIX, msvcrt.locking on Windows."""
|
|
90
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
if lock_path.is_symlink():
|
|
92
|
+
raise SystemExit(f"Refusing to follow symlinked lock file: {lock_path.name}")
|
|
93
|
+
fh = lock_path.open("a+b")
|
|
94
|
+
try:
|
|
95
|
+
try:
|
|
96
|
+
if os.fstat(fh.fileno()).st_size == 0:
|
|
97
|
+
fh.write(b"\0")
|
|
98
|
+
fh.flush()
|
|
99
|
+
except OSError:
|
|
100
|
+
pass
|
|
101
|
+
if fcntl is not None:
|
|
102
|
+
fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
|
|
103
|
+
elif msvcrt is not None:
|
|
104
|
+
_acquire_win_lock(fh.fileno(), timeout_s=timeout_s)
|
|
105
|
+
yield
|
|
106
|
+
finally:
|
|
107
|
+
if fcntl is not None:
|
|
108
|
+
try:
|
|
109
|
+
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
|
|
110
|
+
except OSError:
|
|
111
|
+
pass
|
|
112
|
+
elif msvcrt is not None:
|
|
113
|
+
_release_win_lock(fh.fileno())
|
|
114
|
+
fh.close()
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def atomic_write_text(path: Path, text: str) -> None:
|
|
118
|
+
if path.is_symlink():
|
|
119
|
+
raise SystemExit(f"Refusing to overwrite symlinked file: {path.name}")
|
|
120
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
121
|
+
fd, tmp_name = tempfile.mkstemp(prefix=".tmp_", suffix=path.suffix or ".tmp", dir=str(path.parent))
|
|
122
|
+
try:
|
|
123
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
124
|
+
f.write(text)
|
|
125
|
+
for attempt in range(6):
|
|
126
|
+
try:
|
|
127
|
+
os.replace(tmp_name, path)
|
|
128
|
+
break
|
|
129
|
+
except PermissionError:
|
|
130
|
+
if attempt == 5:
|
|
131
|
+
raise
|
|
132
|
+
time.sleep(0.02 * (attempt + 1))
|
|
133
|
+
except Exception:
|
|
134
|
+
try:
|
|
135
|
+
os.unlink(tmp_name)
|
|
136
|
+
except OSError:
|
|
137
|
+
pass
|
|
138
|
+
raise
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def atomic_write_json(path: Path, obj: Any, *, sort_keys: bool = False) -> None:
|
|
142
|
+
atomic_write_text(path, json.dumps(obj, indent=2, ensure_ascii=False, sort_keys=sort_keys) + "\n")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def git_cmd(repo: Path, args: Sequence[str], timeout: int = 4) -> subprocess.CompletedProcess[str]:
|
|
146
|
+
return subprocess.run(
|
|
147
|
+
["git", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "core.quotepath=false", *args],
|
|
148
|
+
cwd=str(repo),
|
|
149
|
+
capture_output=True,
|
|
150
|
+
text=True,
|
|
151
|
+
encoding="utf-8",
|
|
152
|
+
errors="replace",
|
|
153
|
+
timeout=timeout,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def ensure_git_info_exclude(repo: Path, patterns: Sequence[str] = (".agent-index/", ".agent-state/")) -> bool:
|
|
158
|
+
"""Ensure local AgentEfficiency dirs are excluded in `.git/info/exclude` (worktree-safe, never touches tracked `.gitignore`)."""
|
|
159
|
+
repo_r = repo.resolve()
|
|
160
|
+
try:
|
|
161
|
+
r = git_cmd(repo_r, ["rev-parse", "--git-path", "info/exclude"], timeout=3)
|
|
162
|
+
if r.returncode != 0 or not r.stdout.strip():
|
|
163
|
+
return False
|
|
164
|
+
raw_p = Path(r.stdout.strip())
|
|
165
|
+
excl_path = raw_p if raw_p.is_absolute() else (repo_r / raw_p).resolve()
|
|
166
|
+
if excl_path.is_symlink():
|
|
167
|
+
return False
|
|
168
|
+
existing = excl_path.read_text(encoding="utf-8", errors="replace") if excl_path.is_file() else ""
|
|
169
|
+
existing_lines = {ln.strip() for ln in existing.splitlines() if ln.strip() and not ln.strip().startswith("#")}
|
|
170
|
+
missing = [p for p in patterns if p not in existing_lines and p.rstrip("/") not in existing_lines]
|
|
171
|
+
if not missing:
|
|
172
|
+
return False
|
|
173
|
+
excl_path.parent.mkdir(parents=True, exist_ok=True)
|
|
174
|
+
header = "# AgentEfficiency local artifacts"
|
|
175
|
+
block = ("\n" if existing and not existing.endswith("\n") else "") + (f"\n{header}\n" if header not in existing else "") + "\n".join(missing) + "\n"
|
|
176
|
+
excl_path.write_text(existing + block, encoding="utf-8")
|
|
177
|
+
return True
|
|
178
|
+
except Exception:
|
|
179
|
+
return False
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def sources_fresh(repo: Path, source_files: Dict[str, str]) -> bool:
|
|
183
|
+
repo_r = repo.resolve()
|
|
184
|
+
for rel, old_sha in source_files.items():
|
|
185
|
+
cand = Path(rel)
|
|
186
|
+
if cand.is_absolute() or (repo_r / cand).is_symlink():
|
|
187
|
+
return False
|
|
188
|
+
fp = (repo_r / cand).resolve()
|
|
189
|
+
if not is_within(fp, repo_r) or not fp.is_file():
|
|
190
|
+
return False
|
|
191
|
+
try:
|
|
192
|
+
txt = fp.read_text(encoding="utf-8", errors="replace")
|
|
193
|
+
except OSError:
|
|
194
|
+
return False
|
|
195
|
+
if rel.endswith("DECISIONS.md"):
|
|
196
|
+
txt = txt.split("## Superseded / Archived Decisions", 1)[0].strip()
|
|
197
|
+
if sha256_text(txt)[:16] != old_sha:
|
|
198
|
+
return False
|
|
199
|
+
return True
|