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,496 @@
1
+ #!/usr/bin/env python3
2
+ """AgentEfficiency — Dynamic multi-signal model-tier router with escalation, down-shift & cache-affinity hysteresis."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import re
9
+ import sys
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
13
+
14
+ _SCRIPT_DIR = str(Path(__file__).resolve().parent)
15
+ if _SCRIPT_DIR not in sys.path:
16
+ sys.path.insert(0, _SCRIPT_DIR)
17
+
18
+ from _ae_core import ( # noqa: E402
19
+ ALIAS_TO_TIER,
20
+ atomic_write_json,
21
+ file_lock,
22
+ is_within,
23
+ redact_secrets,
24
+ sources_fresh,
25
+ )
26
+
27
+ CONFIG_PATH = Path(__file__).resolve().parents[1] / "config" / "models.json"
28
+ TIER_ORDER = ["low", "medium", "high", "critical"]
29
+ TIER_RANK = {t: i for i, t in enumerate(TIER_ORDER)}
30
+
31
+
32
+ def load_config(path: Path = CONFIG_PATH) -> Dict[str, Any]:
33
+ return json.loads(path.read_text(encoding="utf-8"))
34
+
35
+
36
+ def _tier_step(tier: str, delta: int) -> str:
37
+ return TIER_ORDER[max(0, min(len(TIER_ORDER) - 1, TIER_RANK.get(tier, 1) + delta))]
38
+
39
+
40
+ def _max_tier(a: str, b: str) -> str:
41
+ return a if TIER_RANK.get(a, 1) >= TIER_RANK.get(b, 1) else b
42
+
43
+
44
+ def _keyword_matches(text_lower: str, keyword: str) -> bool:
45
+ kw = keyword.lower().strip()
46
+ if not kw:
47
+ return False
48
+ if " " in kw or "/" in kw or "." in kw or len(kw) <= 5:
49
+ return bool(re.search(rf"(?<![\w]){re.escape(kw)}(?![\w])", text_lower, flags=re.UNICODE))
50
+ return bool(re.search(rf"(?<![\w]){re.escape(kw)}", text_lower, flags=re.UNICODE))
51
+
52
+
53
+ def _path_matches_sensitive(path_str: str, sens_kw: Sequence[str]) -> bool:
54
+ norm = path_str.replace("\\", "/").lower()
55
+ segments = [seg for seg in re.split(r"[/._-]+", norm) if seg]
56
+ return any((kw.lower() in norm if "/" in kw else kw.lower() in segments) for kw in sens_kw)
57
+
58
+
59
+ def _estimate_turn_cost_usd(tier_cfg: Dict[str, Any], prefix_tokens: int, volatile_input_tokens: int, output_tokens: int, warm_cache: bool) -> float:
60
+ prices = tier_cfg.get("cost_per_1m", {"input": 3.0, "cached_input": 0.3, "output": 15.0})
61
+ p_in = float(prices.get("input", 3.0))
62
+ p_cached = float(prices.get("cached_input", p_in * 0.1))
63
+ p_out = float(prices.get("output", p_in * 5.0))
64
+ return round((prefix_tokens * (p_cached if warm_cache else p_in) + volatile_input_tokens * p_in + output_tokens * p_out) / 1_000_000.0, 6)
65
+
66
+
67
+ def _read_repo_signals(repo: Path) -> Dict[str, Any]:
68
+ signals: Dict[str, Any] = {}
69
+ repo_r = repo.resolve()
70
+ sd = repo_r / ".agent-state"
71
+ if sd.is_symlink() or (sd.exists() and not is_within(sd, repo_r)):
72
+ return signals
73
+
74
+ sf = sd / "state.json"
75
+ if sf.is_file() and not sf.is_symlink():
76
+ try:
77
+ st = json.loads(sf.read_text(encoding="utf-8"))
78
+ tid = st.get("active_task")
79
+ if tid and tid in st.get("tasks", {}):
80
+ t = st["tasks"][tid]
81
+ signals.update({
82
+ "active_task_id": tid, "current_tier": t.get("model_tier"),
83
+ "failures": int(t.get("failures_count", 0)),
84
+ "touched_paths": list(t.get("files_touched", t.get("files", []))),
85
+ "human_approval_required": bool(t.get("human_approval_required", False) or t.get("model_tier") == "critical"),
86
+ })
87
+ except Exception:
88
+ pass
89
+
90
+ cf = sd / "cache_registry.json"
91
+ if cf.is_file() and not cf.is_symlink():
92
+ try:
93
+ reg = json.loads(cf.read_text(encoding="utf-8"))
94
+ now_ts = time.time()
95
+ best: Optional[Tuple[int, str, str, int]] = None
96
+ for pname, pentry in reg.get("prefixes", {}).items():
97
+ cur_pid = pentry.get("prefix_id")
98
+ if pentry.get("source_files") and not sources_fresh(repo_r, pentry["source_files"]):
99
+ continue
100
+ toks = int(pentry.get("combined_tokens_est", 0))
101
+ for skey, s in pentry.get("sessions", {}).items():
102
+ exp = s.get("expires_at")
103
+ if exp and exp > now_ts and (not s.get("prefix_id") or s.get("prefix_id") == cur_pid):
104
+ tier = ALIAS_TO_TIER.get(str(s.get("tier") or "medium").lower(), "medium")
105
+ if best is None or toks > best[0]:
106
+ best = (toks, tier, f"{pname} ({skey})", int(exp - now_ts))
107
+ if best:
108
+ signals.update({"warm_prefix_tokens": best[0], "warm_cache_tier": best[1], "warm_cache_source": best[2], "warm_cache_ttl_remaining": best[3]})
109
+ except Exception:
110
+ pass
111
+ return signals
112
+
113
+
114
+ def _record_route_in_state(repo: Path, decision: Dict[str, Any], task_label: str) -> None:
115
+ sd = repo.resolve() / ".agent-state"
116
+ sf = sd / "state.json"
117
+ if sd.is_symlink() or sf.is_symlink() or not sf.is_file():
118
+ return
119
+ try:
120
+ with file_lock(sd / ".state.lock"):
121
+ st = json.loads(sf.read_text(encoding="utf-8"))
122
+ tid = st.get("active_task")
123
+ if not tid or tid not in st.get("tasks", {}):
124
+ return
125
+ t = st["tasks"][tid]
126
+ prev = t.get("model_tier")
127
+ t["model_tier"], t["model_alias"] = decision["tier"], decision["model_alias"]
128
+ if decision.get("human_approval_required"):
129
+ t["human_approval_required"] = True
130
+ t.setdefault("routing_history", []).append({
131
+ "at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "from_tier": prev, "to_tier": decision["tier"],
132
+ "action": decision["action"], "task": redact_secrets(task_label)[:160], "reasons": decision["reasons"][:5],
133
+ })
134
+ telem = st.setdefault("telemetry", {})
135
+ 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)):
136
+ telem.setdefault(k, dv)
137
+ telem.setdefault("by_tier", {})
138
+ if prev and prev != decision["tier"]:
139
+ telem["model_switches"] = int(telem.get("model_switches", 0)) + 1
140
+ st["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
141
+ atomic_write_json(sf, st)
142
+ try:
143
+ import state_render as _sr # type: ignore
144
+ _sr.render_current_state(sd, st)
145
+ _sr.render_task_queue(sd, st)
146
+ except Exception:
147
+ pass
148
+ except Exception:
149
+ pass
150
+
151
+
152
+ def _resolve_runtime_model(cfg: Dict[str, Any], tier: str, runtime: Optional[str]) -> Tuple[Optional[str], Optional[str]]:
153
+ eff_rt = (runtime or os.getenv("AGENT_EFFICIENCY_RUNTIME") or "").strip().lower() or None
154
+ if not eff_rt or eff_rt == "env":
155
+ return eff_rt, None
156
+ presets = cfg.get("runtime_presets", {})
157
+ rt_map = presets.get(eff_rt)
158
+ if isinstance(rt_map, dict):
159
+ return eff_rt, rt_map.get(tier)
160
+ return eff_rt, None
161
+
162
+
163
+ def choose(
164
+ task: str,
165
+ complexity: str = "auto",
166
+ risk: str = "medium",
167
+ cfg: Optional[Dict[str, Any]] = None,
168
+ *,
169
+ phase: Optional[str] = None,
170
+ current_tier: Optional[str] = None,
171
+ failures: int = 0,
172
+ files_count: int = 0,
173
+ dependents_count: int = 0,
174
+ estimated_diff_lines: int = 0,
175
+ context_tokens: int = 0,
176
+ touched_paths: Sequence[str] = (),
177
+ uncertainty: str = "low",
178
+ budget_mode: str = "normal",
179
+ warm_cache_tier: Optional[str] = None,
180
+ warm_prefix_tokens: int = 0,
181
+ expected_subsequent_turns: int = 1,
182
+ runtime: Optional[str] = None,
183
+ ) -> Dict[str, Any]:
184
+ cfg = cfg or load_config()
185
+ rules, esc, phase_bias = cfg.get("routing", {}), cfg.get("escalation", {}), cfg.get("phase_bias", {})
186
+ t_low = task.lower()
187
+ reasons: List[str] = []
188
+ score = 0
189
+
190
+ crit_hits = [k for k in rules.get("critical_keywords", []) if _keyword_matches(t_low, k)]
191
+ risk_hits = [k for k in rules.get("high_risk_keywords", []) if _keyword_matches(t_low, k)]
192
+ comp_hits = [k for k in rules.get("high_complexity_keywords", []) if _keyword_matches(t_low, k)]
193
+ low_hits = [k for k in rules.get("low_complexity_keywords", []) if _keyword_matches(t_low, k)]
194
+
195
+ if risk in ("high", "critical"):
196
+ reasons.append(f"explicit risk='{risk}'")
197
+ if crit_hits:
198
+ score += 6
199
+ reasons.append(f"critical keywords: {', '.join(crit_hits[:3])}")
200
+ if risk_hits:
201
+ score += 3 * len(risk_hits)
202
+ reasons.append(f"high-risk keywords: {', '.join(risk_hits[:4])}")
203
+ if comp_hits:
204
+ score += 2 * len(comp_hits)
205
+ reasons.append(f"complexity keywords: {', '.join(comp_hits[:4])}")
206
+ if low_hits:
207
+ score -= len(low_hits)
208
+ reasons.append(f"routine keywords: {', '.join(low_hits[:4])}")
209
+
210
+ sensitive_paths = [p for p in touched_paths if _path_matches_sensitive(p, rules.get("sensitive_path_keywords", []))]
211
+ if sensitive_paths:
212
+ score += 3
213
+ reasons.append(f"sensitive paths: {', '.join(sensitive_paths[:3])}")
214
+ if phase and phase in phase_bias:
215
+ pb = int(phase_bias[phase])
216
+ score += pb
217
+ reasons.append(f"phase '{phase}' ({pb:+d})")
218
+
219
+ for val, hi_t, md_t, hi_pts, md_pts, lbl in (
220
+ (files_count, int(esc.get("files_high_threshold", 8)), int(esc.get("files_medium_threshold", 3)), 3, 1, "files"),
221
+ (dependents_count, int(esc.get("dependents_high_threshold", 10)), int(esc.get("dependents_medium_threshold", 4)), 3, 1, "dependents"),
222
+ (estimated_diff_lines, int(esc.get("diff_lines_high_threshold", 450)), int(esc.get("diff_lines_medium_threshold", 150)), 2, 1, "diff lines"),
223
+ ):
224
+ if val >= hi_t:
225
+ score += hi_pts
226
+ reasons.append(f"high scope ({val} {lbl})")
227
+ elif val >= md_t:
228
+ score += md_pts
229
+ reasons.append(f"moderate scope ({val} {lbl})")
230
+
231
+ if context_tokens >= 40000:
232
+ score += 1
233
+ reasons.append(f"heavy context (~{context_tokens:,} tok)")
234
+ if uncertainty in ("medium", "high"):
235
+ score += 2 if uncertainty == "high" else 1
236
+ reasons.append(f"{uncertainty} uncertainty")
237
+
238
+ high_threshold = 4 if budget_mode == "frugal" else (5 if budget_mode == "strict" else 3)
239
+ if complexity != "auto":
240
+ tier = complexity
241
+ reasons.append(f"explicit complexity override: {complexity}")
242
+ elif risk == "critical" or crit_hits:
243
+ tier = "critical"
244
+ elif risk == "high" or score >= high_threshold:
245
+ tier = "high"
246
+ elif (score < 0 or (score == 0 and risk == "low")) and not sensitive_paths and not risk_hits and not comp_hits:
247
+ tier = "low"
248
+ else:
249
+ tier = "medium"
250
+
251
+ if risk == "critical" or crit_hits:
252
+ tier = "critical"
253
+ elif (risk == "high" or sensitive_paths) and TIER_RANK[tier] < TIER_RANK["high"]:
254
+ tier = "high"
255
+ reasons.append("elevated to high by risk/sensitive-path floor")
256
+
257
+ escalate_to_human = False
258
+ if failures > 0:
259
+ base = current_tier or tier
260
+ if base == "low" and failures >= int(esc.get("upshift_after_failures", 1)):
261
+ tier = _max_tier(tier, "high" if failures >= int(esc.get("high_tier_after_failures", 2)) else "medium")
262
+ reasons.append(f"failure escalation ({failures} failure(s) from low -> {tier})")
263
+ elif base == "medium" and failures >= int(esc.get("high_tier_after_failures", 2)):
264
+ tier = _max_tier(tier, "high")
265
+ reasons.append(f"2-attempt escalation ({failures} failures on medium -> high)")
266
+ elif base in ("high", "critical") and failures >= int(esc.get("human_escalation_after_high_failures", 2)):
267
+ tier = _max_tier(tier, base)
268
+ escalate_to_human = True
269
+ reasons.append(f"repeated failures on {base} ({failures}) — stop tweaking and request root-cause reset / human review")
270
+
271
+ recommended_tier, cache_note, stayed_warm = tier, None, False
272
+ vol_in = int(esc.get("assumed_volatile_input_tokens", 1500))
273
+ est_out = int(esc.get("assumed_turn_output_tokens", 1200))
274
+ turns = max(1, expected_subsequent_turns)
275
+ norm_warm = ALIAS_TO_TIER.get((warm_cache_tier or "").lower()) if warm_cache_tier else None
276
+
277
+ if norm_warm and norm_warm in cfg["tiers"] and warm_prefix_tokens >= 1024 and TIER_RANK[tier] < TIER_RANK[norm_warm] and not escalate_to_human:
278
+ stay_cost = _estimate_turn_cost_usd(cfg["tiers"][norm_warm], warm_prefix_tokens, vol_in, est_out, True) * turns
279
+ sw_cost = _estimate_turn_cost_usd(cfg["tiers"][tier], warm_prefix_tokens, vol_in, est_out, False) + (
280
+ _estimate_turn_cost_usd(cfg["tiers"][tier], warm_prefix_tokens, vol_in, est_out, True) * (turns - 1) if turns > 1 else 0.0
281
+ )
282
+ if stay_cost < sw_cost:
283
+ stayed_warm, recommended_tier = True, norm_warm
284
+ cache_note = f"Kept warm '{norm_warm}' cache (~{warm_prefix_tokens:,} tok): stay ~${stay_cost:.5f} vs switch to '{tier}' ~${sw_cost:.5f} over {turns} turn(s)."
285
+ reasons.append(f"cache-affinity kept warm tier '{norm_warm}'")
286
+ else:
287
+ cache_note = f"Downshift to '{tier}' is economical even with warm '{norm_warm}' cache (switch ~${sw_cost:.5f} <= stay ~${stay_cost:.5f})."
288
+
289
+ if escalate_to_human:
290
+ action = "require_human"
291
+ elif stayed_warm:
292
+ action = "stay_warm_cache"
293
+ elif current_tier and current_tier in TIER_RANK:
294
+ action = "upshift" if TIER_RANK[recommended_tier] > TIER_RANK[current_tier] else ("downshift" if TIER_RANK[recommended_tier] < TIER_RANK[current_tier] else "keep")
295
+ else:
296
+ action = "select"
297
+
298
+ entry = cfg["tiers"][recommended_tier]
299
+ ev = entry.get("env_var", f"AGENT_MODEL_{entry['alias'].upper()}")
300
+ fev = entry.get("fallback_env_var", f"{ev}_FALLBACK")
301
+ eff_rt, rt_model = _resolve_runtime_model(cfg, recommended_tier, runtime)
302
+ resolved_model = os.getenv(ev) or rt_model or None
303
+ est_cost = _estimate_turn_cost_usd(entry, warm_prefix_tokens, vol_in, est_out, warm_cache=(norm_warm == recommended_tier and warm_prefix_tokens >= 1024))
304
+ hi_base = _estimate_turn_cost_usd(cfg["tiers"]["high"], warm_prefix_tokens, vol_in, est_out, False)
305
+ return {
306
+ "tier": recommended_tier, "raw_target_tier": tier, "model_alias": entry["alias"],
307
+ "env_var": ev, "resolved_model": resolved_model,
308
+ "runtime": eff_rt, "runtime_model": rt_model,
309
+ "fallback_env_var": fev, "fallback_model": os.getenv(fev) or None,
310
+ "action": action, "previous_tier": current_tier, "reason_score": score,
311
+ "reasons": reasons or ["default balanced routing"],
312
+ "human_approval_required": recommended_tier == "critical" or escalate_to_human,
313
+ "independent_review_required": recommended_tier in ("high", "critical") and (risk in ("high", "critical") or bool(sensitive_paths)),
314
+ "description": entry["description"], "cache_affinity_note": cache_note,
315
+ "estimated_turn_cost_usd": est_cost,
316
+ "vs_always_reasoning_savings_pct": round(max(0.0, (1.0 - est_cost / max(1e-9, hi_base)) * 100), 1),
317
+ }
318
+
319
+
320
+ def route_plan(steps: Sequence[str], cfg: Dict[str, Any], risk: str = "medium", budget_mode: str = "normal", runtime: Optional[str] = None) -> Dict[str, Any]:
321
+ routed, tot_r, tot_h, prev = [], 0.0, 0.0, None
322
+ for idx, step in enumerate(steps, start=1):
323
+ dec = choose(step, "auto", risk, cfg, current_tier=prev, budget_mode=budget_mode, runtime=runtime)
324
+ prev = dec["tier"]
325
+ tot_r += dec["estimated_turn_cost_usd"]
326
+ tot_h += _estimate_turn_cost_usd(cfg["tiers"]["high"], 0, 1500, 1200, False)
327
+ step_entry = {"step": idx, "task": step, "tier": dec["tier"], "model_alias": dec["model_alias"], "action": dec["action"], "reasons": dec["reasons"][:3]}
328
+ if dec.get("resolved_model"):
329
+ step_entry["resolved_model"] = dec["resolved_model"]
330
+ routed.append(step_entry)
331
+ return {
332
+ "step_count": len(routed), "runtime": runtime or os.getenv("AGENT_EFFICIENCY_RUNTIME") or None,
333
+ "tier_distribution": {t: sum(1 for s in routed if s["tier"] == t) for t in TIER_ORDER if any(s["tier"] == t for s in routed)},
334
+ "estimated_routed_cost_usd": round(tot_r, 6), "estimated_always_reasoning_cost_usd": round(tot_h, 6),
335
+ "estimated_cost_savings_pct": round(max(0.0, (1.0 - tot_r / max(1e-9, tot_h)) * 100), 1), "steps": routed,
336
+ }
337
+
338
+
339
+ def check_models(cfg: Dict[str, Any], runtime: Optional[str] = None) -> Dict[str, Any]:
340
+ aliases: Dict[str, Dict[str, Any]] = {}
341
+ eff_rt = (runtime or os.getenv("AGENT_EFFICIENCY_RUNTIME") or "").strip().lower() or None
342
+ for tier_name, entry in cfg["tiers"].items():
343
+ al = entry["alias"]
344
+ if al in aliases:
345
+ continue
346
+ ev = entry.get("env_var", f"AGENT_MODEL_{al.upper()}")
347
+ fev = entry.get("fallback_env_var", f"{ev}_FALLBACK")
348
+ _, rt_m = _resolve_runtime_model(cfg, tier_name, eff_rt)
349
+ eff_m = os.getenv(ev) or rt_m or None
350
+ aliases[al] = {"env_var": ev, "configured": bool(eff_m), "model": eff_m, "runtime_model": rt_m, "fallback_env_var": fev, "fallback_configured": bool(os.getenv(fev)), "fallback_model": os.getenv(fev) or None}
351
+ return {"runtime": eff_rt, "available_runtimes": sorted(cfg.get("runtime_presets", {}).keys()), "all_primary_configured": all(v["configured"] for v in aliases.values()), "aliases": aliases}
352
+
353
+
354
+ def main(argv: Optional[Sequence[str]] = None) -> int:
355
+ raw = list(sys.argv[1:] if argv is None else argv)
356
+ if raw and raw[0] not in {"route", "escalate", "downshift", "plan", "check-models", "-h", "--help"}:
357
+ raw = ["route"] + raw
358
+
359
+ ap = argparse.ArgumentParser(description="AgentEfficiency adaptive model-tier router.")
360
+ sub = ap.add_subparsers(dest="cmd", required=True)
361
+
362
+ p = sub.add_parser("route", help="Recommend or switch model tier")
363
+ p.add_argument("repo_pos", nargs="?", type=Path, default=None, help="Optional positional repository path (alternative to --repo)")
364
+ p.add_argument("--task", required=True)
365
+ p.add_argument("--complexity", choices=["auto", "low", "medium", "high", "critical"], default="auto")
366
+ p.add_argument("--risk", choices=["low", "medium", "high", "critical"], default="medium")
367
+ p.add_argument("--phase", default=None)
368
+ p.add_argument("--current-tier", choices=TIER_ORDER, default=None)
369
+ p.add_argument("--failures", type=int, default=None)
370
+ p.add_argument("--files-count", type=int, default=0)
371
+ p.add_argument("--dependents-count", type=int, default=0)
372
+ p.add_argument("--diff-lines", type=int, default=0)
373
+ p.add_argument("--context-tokens", type=int, default=0)
374
+ p.add_argument("--touched-paths", default="")
375
+ p.add_argument("--uncertainty", choices=["low", "medium", "high"], default="low")
376
+ p.add_argument("--budget-mode", choices=["normal", "frugal", "strict"], default="normal")
377
+ p.add_argument("--warm-cache-tier", choices=TIER_ORDER, default=None)
378
+ p.add_argument("--warm-prefix-tokens", type=int, default=None)
379
+ p.add_argument("--expected-turns", type=int, default=1)
380
+ p.add_argument("--repo", type=Path, default=None)
381
+ p.add_argument("--runtime", choices=["env", "antigravity", "claude", "codex", "gemini"], default=None, help="Map tiers to IDE subagent model names")
382
+ p.add_argument("--record", action="store_true")
383
+ p.add_argument("--config", type=Path, default=CONFIG_PATH)
384
+
385
+ p = sub.add_parser("escalate", help="Escalate active task tier by +1 (respects 2-Attempt Rule before critical)")
386
+ p.add_argument("repo", type=Path)
387
+ p.add_argument("--reason", required=True)
388
+ p.add_argument("--force-critical", action="store_true", help="Escalate high -> critical immediately regardless of failure count")
389
+ p.add_argument("--runtime", choices=["env", "antigravity", "claude", "codex", "gemini"], default=None)
390
+ p.add_argument("--config", type=Path, default=CONFIG_PATH)
391
+
392
+ p = sub.add_parser("downshift", help="Check safe & cache-economical down-shift")
393
+ p.add_argument("repo", type=Path)
394
+ p.add_argument("--task", required=True)
395
+ p.add_argument("--phase", default="format")
396
+ p.add_argument("--expected-turns", type=int, default=1)
397
+ p.add_argument("--isolated-subtask", action="store_true", help="Route isolated low-risk subagent without altering parent task's governance gate")
398
+ p.add_argument("--override-critical", action="store_true", help="Explicitly allow down-shifting a critical/human-gated task")
399
+ p.add_argument("--runtime", choices=["env", "antigravity", "claude", "codex", "gemini"], default=None)
400
+ p.add_argument("--record", action="store_true")
401
+ p.add_argument("--config", type=Path, default=CONFIG_PATH)
402
+
403
+ p = sub.add_parser("plan", help="Route pipe-separated plan steps")
404
+ p.add_argument("--steps", required=True)
405
+ p.add_argument("--risk", choices=["low", "medium", "high", "critical"], default="medium")
406
+ p.add_argument("--budget-mode", choices=["normal", "frugal", "strict"], default="normal")
407
+ p.add_argument("--runtime", choices=["env", "antigravity", "claude", "codex", "gemini"], default=None)
408
+ p.add_argument("--config", type=Path, default=CONFIG_PATH)
409
+
410
+ p_cm = sub.add_parser("check-models", help="Check AGENT_MODEL_* env vars or IDE runtime presets")
411
+ p_cm.add_argument("--runtime", choices=["env", "antigravity", "claude", "codex", "gemini"], default=None)
412
+ p_cm.add_argument("--config", type=Path, default=CONFIG_PATH)
413
+
414
+ args = ap.parse_args(raw)
415
+ cfg = load_config(args.config)
416
+
417
+ if args.cmd == "check-models":
418
+ print(json.dumps(check_models(cfg, runtime=args.runtime), indent=2))
419
+ elif args.cmd == "plan":
420
+ print(json.dumps(route_plan([s.strip() for s in args.steps.split("|") if s.strip()], cfg, risk=args.risk, budget_mode=args.budget_mode, runtime=args.runtime), indent=2))
421
+ elif args.cmd == "escalate":
422
+ sig = _read_repo_signals(args.repo)
423
+ cur = sig.get("current_tier") or "medium"
424
+ fails = int(sig.get("failures", 0))
425
+ min_hi_fails = int(cfg.get("escalation", {}).get("human_escalation_after_high_failures", 2))
426
+ if cur == "high" and not args.force_critical and fails < min_hi_fails:
427
+ nxt = "high"
428
+ action = "require_human"
429
+ needs_human = True
430
+ reasons = [f"manual/runtime escalation on high (failures={fails} < {min_hi_fails}): {args.reason} — keeping tier 'high' with human review gate (pass --force-critical for critical tier)"]
431
+ else:
432
+ nxt = _tier_step(cur, 1)
433
+ action = "require_human" if cur in ("high", "critical") else "upshift"
434
+ needs_human = nxt == "critical" or cur in ("high", "critical")
435
+ reasons = [f"manual/runtime escalation: {args.reason}"]
436
+ e = cfg["tiers"][nxt]
437
+ eff_rt, rt_m = _resolve_runtime_model(cfg, nxt, args.runtime)
438
+ dec = {
439
+ "tier": nxt, "raw_target_tier": nxt, "model_alias": e["alias"],
440
+ "env_var": e.get("env_var"), "resolved_model": os.getenv(e.get("env_var", "")) or rt_m or None,
441
+ "runtime": eff_rt, "runtime_model": rt_m,
442
+ "action": action, "previous_tier": cur, "reasons": reasons,
443
+ "human_approval_required": needs_human, "description": e["description"],
444
+ }
445
+ _record_route_in_state(args.repo, dec, f"escalate: {args.reason}")
446
+ print(json.dumps(dec, indent=2))
447
+ elif args.cmd == "downshift":
448
+ sig = _read_repo_signals(args.repo)
449
+ cur = sig.get("current_tier") or "high"
450
+ # Governance invariant: never silently clear a critical / human-approval gate on the active task!
451
+ if (cur == "critical" or sig.get("human_approval_required")) and not args.isolated_subtask and not args.override_critical:
452
+ e = cfg["tiers"]["critical" if cur == "critical" else cur]
453
+ eff_rt, rt_m = _resolve_runtime_model(cfg, cur, args.runtime)
454
+ dec = {
455
+ "tier": cur, "raw_target_tier": cur, "model_alias": e["alias"],
456
+ "env_var": e.get("env_var"), "resolved_model": os.getenv(e.get("env_var", "")) or rt_m or None,
457
+ "runtime": eff_rt, "runtime_model": rt_m,
458
+ "action": "blocked_by_governance", "previous_tier": cur,
459
+ "reasons": ["Cannot downshift a critical/human-gated task in place; pass --isolated-subtask for a separate low-risk subagent or --override-critical after human approval."],
460
+ "human_approval_required": True, "independent_review_required": True, "description": e["description"],
461
+ }
462
+ print(json.dumps(dec, indent=2))
463
+ return 0
464
+ dec = choose(
465
+ args.task, "auto", "low", cfg, phase=args.phase, current_tier=cur,
466
+ failures=0 if args.isolated_subtask else int(sig.get("failures", 0)),
467
+ touched_paths=() if args.isolated_subtask else sig.get("touched_paths", []),
468
+ warm_cache_tier=sig.get("warm_cache_tier"), warm_prefix_tokens=int(sig.get("warm_prefix_tokens", 0)),
469
+ expected_subsequent_turns=args.expected_turns, runtime=args.runtime,
470
+ )
471
+ if args.record and not args.isolated_subtask:
472
+ _record_route_in_state(args.repo, dec, args.task)
473
+ print(json.dumps(dec, indent=2))
474
+ else:
475
+ repo = args.repo or args.repo_pos
476
+ sig = _read_repo_signals(repo) if repo else {}
477
+ touched = [x.strip() for x in args.touched_paths.split(",") if x.strip()] or sig.get("touched_paths", [])
478
+ dec = choose(
479
+ args.task, args.complexity, args.risk, cfg, phase=args.phase,
480
+ current_tier=args.current_tier or sig.get("current_tier"),
481
+ failures=args.failures if args.failures is not None else int(sig.get("failures", 0)),
482
+ files_count=args.files_count or len(touched), dependents_count=args.dependents_count,
483
+ estimated_diff_lines=args.diff_lines, context_tokens=args.context_tokens,
484
+ touched_paths=touched, uncertainty=args.uncertainty, budget_mode=args.budget_mode,
485
+ warm_cache_tier=args.warm_cache_tier or sig.get("warm_cache_tier"),
486
+ warm_prefix_tokens=args.warm_prefix_tokens if args.warm_prefix_tokens is not None else int(sig.get("warm_prefix_tokens", 0)),
487
+ expected_subsequent_turns=args.expected_turns, runtime=args.runtime,
488
+ )
489
+ if repo and args.record:
490
+ _record_route_in_state(repo, dec, args.task)
491
+ print(json.dumps(dec, indent=2))
492
+ return 0
493
+
494
+
495
+ if __name__ == "__main__":
496
+ raise SystemExit(main())