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,306 @@
1
+ """AgentEfficiency — Provider-aware LLM adapter with caching, fallback, escalation & telemetry.
2
+
3
+ Works offline for `prepare_request()` and `parse_provider_usage()` (stdlib only).
4
+ Actual completion calls require optional `litellm` (`pip install litellm`).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ import re
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+ from typing import Any, Dict, List, Optional, Tuple
15
+
16
+ _SCRIPT_DIR = str(Path(__file__).resolve().parent)
17
+ if _SCRIPT_DIR not in sys.path:
18
+ sys.path.insert(0, _SCRIPT_DIR)
19
+
20
+ from _ae_core import ( # noqa: E402, F401
21
+ ALIAS_TO_TIER,
22
+ DEFAULT_TIER_PRICES,
23
+ PROVIDER_DEFAULTS,
24
+ atomic_write_json,
25
+ canonicalize_text as _canonicalize,
26
+ compute_prefix_id,
27
+ detect_provider as _shared_detect_provider,
28
+ file_lock,
29
+ frame_untrusted_data as _frame_data,
30
+ min_cache_tokens_for_model,
31
+ parse_provider_usage,
32
+ redact_secrets as _redact,
33
+ usage_to_dict as _usage_to_dict,
34
+ )
35
+
36
+ ENV_BY_ALIAS: Dict[str, str] = {
37
+ "fast": "AGENT_MODEL_FAST",
38
+ "balanced": "AGENT_MODEL_BALANCED",
39
+ "reasoning": "AGENT_MODEL_REASONING",
40
+ }
41
+ FALLBACK_ENV_BY_ALIAS: Dict[str, str] = {
42
+ "fast": "AGENT_MODEL_FAST_FALLBACK",
43
+ "balanced": "AGENT_MODEL_BALANCED_FALLBACK",
44
+ "reasoning": "AGENT_MODEL_REASONING_FALLBACK",
45
+ }
46
+ ALIAS_ESCALATION_CHAIN: List[str] = ["fast", "balanced", "reasoning"]
47
+
48
+ _CACHE_BUSTER_RE = re.compile(
49
+ r"(?:\b20\d{2}-\d{2}-\d{2}[T ]\d{2}:\d{2}"
50
+ 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"
51
+ r"|(?i:\b(?:turn|iteration|attempt|retry)\s*(?:#|:)?\s*\d+\b(?!\s+times\b)))"
52
+ )
53
+
54
+
55
+ def detect_provider(model: str) -> str:
56
+ return _shared_detect_provider(model, None, default_when_empty="litellm")
57
+
58
+
59
+ def lint_stable_prefix(stable_prefix: str, provider: str = "anthropic", model: str = "") -> List[str]:
60
+ warnings: List[str] = []
61
+ if not stable_prefix:
62
+ return warnings
63
+ for idx, line in enumerate(stable_prefix.splitlines(), start=1):
64
+ m = _CACHE_BUSTER_RE.search(line)
65
+ if m:
66
+ warnings.append(f"Line {idx}: volatile token '{m.group(0)[:40]}' may bust provider prompt cache.")
67
+ est_tokens = max(1, (len(stable_prefix) + 3) // 4)
68
+ min_tok = min_cache_tokens_for_model(provider, model)
69
+ if est_tokens < min_tok:
70
+ warnings.append(f"Stable prefix is ~{est_tokens} tokens (<{min_tok}); provider caching may not activate yet.")
71
+ return warnings
72
+
73
+
74
+ def prepare_request(
75
+ model: str,
76
+ stable_prefix: str,
77
+ dynamic_context: str,
78
+ user_task: str,
79
+ *,
80
+ project_prefix: str = "",
81
+ cache_ttl: str = "5m",
82
+ strict_cache_lint: bool = False,
83
+ ) -> Dict[str, Any]:
84
+ raw_l0 = _canonicalize(stable_prefix)
85
+ raw_l1 = _canonicalize(project_prefix)
86
+ provider = detect_provider(model)
87
+ warnings = lint_stable_prefix("\n".join(p for p in (raw_l0, raw_l1) if p), provider=provider, model=model)
88
+ if strict_cache_lint and any("volatile token" in w for w in warnings):
89
+ raise ValueError(f"Cache-buster detected in stable prefix: {warnings}")
90
+
91
+ l0 = _canonicalize(_redact(raw_l0))
92
+ l1 = _canonicalize(_redact(raw_l1))
93
+ prefix_id, _ = compute_prefix_id(l0, l1)
94
+ extra_kwargs: Dict[str, Any] = {}
95
+ messages: List[Dict[str, Any]] = []
96
+ l1_framed = _frame_data("L1_PROJECT", l1) if l1 else ""
97
+
98
+ if provider in ("anthropic", "bedrock"):
99
+ cc: Dict[str, Any] = {"type": "ephemeral"}
100
+ if cache_ttl == "1h" and provider == "anthropic":
101
+ cc["ttl"] = "1h"
102
+ blocks: List[Dict[str, Any]] = []
103
+ if l0:
104
+ blocks.append({"type": "text", "text": l0, "cache_control": dict(cc)})
105
+ if l1_framed:
106
+ blocks.append({"type": "text", "text": l1_framed, "cache_control": dict(cc)})
107
+ if blocks:
108
+ messages.append({"role": "system", "content": blocks})
109
+ else:
110
+ prefix_text = "\n\n".join(p for p in (l0, l1_framed) if p)
111
+ if prefix_text:
112
+ messages.append({"role": "system", "content": prefix_text})
113
+ if provider == "openai":
114
+ extra_kwargs["prompt_cache_key"] = prefix_id
115
+
116
+ dyn_clean = _redact(dynamic_context.strip())
117
+ dyn_framed = _frame_data("L2_VOLATILE", dyn_clean).strip() if dyn_clean else ""
118
+ combined_user = "\n\n".join(p for p in (dyn_framed, _redact(user_task.strip())) if p)
119
+ messages.append({"role": "user", "content": combined_user})
120
+
121
+ return {
122
+ "model": model, "provider": provider, "prefix_id": prefix_id,
123
+ "messages": messages, "extra_kwargs": extra_kwargs, "lint_warnings": warnings,
124
+ }
125
+
126
+
127
+ def _persist_cache_telemetry(
128
+ repo: Path,
129
+ prefix_name: str,
130
+ prefix_id: str,
131
+ provider: str,
132
+ model: str,
133
+ alias: str,
134
+ parsed: Dict[str, Any],
135
+ ttl_seconds: Optional[int] = None,
136
+ cache_ttl: str = "5m",
137
+ ) -> None:
138
+ sd = repo.resolve() / ".agent-state"
139
+ reg_path = sd / "cache_registry.json"
140
+ if sd.is_symlink() or reg_path.is_symlink():
141
+ return
142
+
143
+ pinfo = PROVIDER_DEFAULTS.get(provider, PROVIDER_DEFAULTS["litellm"])
144
+ ttl = int(ttl_seconds or pinfo["default_ttl_seconds"])
145
+ tier = ALIAS_TO_TIER.get(alias, "medium")
146
+ unit_price, _p_cached_default, out_price = DEFAULT_TIER_PRICES[tier]
147
+ read_disc = float(pinfo["cache_read_discount"])
148
+ write_prem = float(pinfo["extended_cache_write_premium"] if cache_ttl == "1h" else pinfo["cache_write_premium"])
149
+ net_savings = (
150
+ parsed["cache_read_tokens"] * unit_price * read_disc
151
+ - parsed["cache_write_tokens"] * unit_price * write_prem
152
+ ) / 1_000_000.0
153
+
154
+ with file_lock(sd / ".cache.lock"):
155
+ try:
156
+ reg = json.loads(reg_path.read_text(encoding="utf-8")) if reg_path.is_file() else {"schema_version": 1, "prefixes": {}}
157
+ except Exception:
158
+ reg = {"schema_version": 1, "prefixes": {}}
159
+
160
+ tot = reg.setdefault("totals", {})
161
+ for k, dv in (("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)):
162
+ tot.setdefault(k, dv)
163
+ is_hit = bool(parsed["cache_verified"] and parsed["cache_read_tokens"] > 0)
164
+ tot["calls"] += 1
165
+ tot["verified_cache_hits" if is_hit else "cache_misses"] += 1
166
+ tot["input_tokens"] += parsed["input_tokens"]
167
+ tot["cache_read_tokens"] += parsed["cache_read_tokens"]
168
+ tot["cache_write_tokens"] += parsed["cache_write_tokens"]
169
+ tot["output_tokens"] += parsed["output_tokens"]
170
+ tot["estimated_savings_usd"] = round(float(tot["estimated_savings_usd"]) + net_savings, 6)
171
+
172
+ now_ts = time.time()
173
+ entry = reg.setdefault("prefixes", {}).setdefault(
174
+ prefix_name,
175
+ {"name": prefix_name, "prefix_id": prefix_id, "combined_tokens_est": parsed["cache_read_tokens"] or parsed["input_tokens"], "source_files": {}, "version": 1, "sessions": {}},
176
+ )
177
+ entry["prefix_id"] = prefix_id
178
+ skey = f"{provider}:{model}"
179
+ sess = entry.setdefault("sessions", {}).setdefault(
180
+ skey, {"provider": provider, "model": model, "prefix_id": prefix_id, "hits": 0, "misses": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "input_tokens": 0, "output_tokens": 0, "estimated_savings_usd": 0.0}
181
+ )
182
+ sess.update({"prefix_id": prefix_id, "tier": tier, "ttl_seconds": ttl, "last_used_at": now_ts, "expires_at": now_ts + ttl})
183
+ sess["hits" if is_hit else "misses"] += 1
184
+ sess["cache_read_tokens"] += parsed["cache_read_tokens"]
185
+ sess["cache_write_tokens"] += parsed["cache_write_tokens"]
186
+ sess["input_tokens"] = int(sess.get("input_tokens", 0)) + parsed["input_tokens"]
187
+ sess["output_tokens"] = int(sess.get("output_tokens", 0)) + parsed["output_tokens"]
188
+ sess["estimated_savings_usd"] = round(float(sess.get("estimated_savings_usd", 0.0)) + net_savings, 6)
189
+ reg["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
190
+ atomic_write_json(reg_path, reg, sort_keys=True)
191
+
192
+ # Also sync telemetry into `.agent-state/state.json` when present (parity with prompt_cache.py)
193
+ sf = sd / "state.json"
194
+ if sf.is_file() and not sf.is_symlink():
195
+ try:
196
+ with file_lock(sd / ".state.lock"):
197
+ st = json.loads(sf.read_text(encoding="utf-8"))
198
+ telem = st.setdefault("telemetry", {})
199
+ 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)):
200
+ telem.setdefault(k, dv)
201
+ by_tier = telem.setdefault("by_tier", {})
202
+ eff_cached_price = unit_price * (1.0 - read_disc)
203
+ actual = (max(0, parsed["input_tokens"] - parsed["cache_read_tokens"]) * unit_price + parsed["cache_read_tokens"] * eff_cached_price + parsed["cache_write_tokens"] * (unit_price * write_prem) + parsed["output_tokens"] * out_price) / 1_000_000.0
204
+ r_in, _rc, r_out = DEFAULT_TIER_PRICES["high"]
205
+ vs_base = max(0.0, (parsed["input_tokens"] * r_in + parsed["output_tokens"] * r_out) / 1_000_000.0 - actual)
206
+ telem["calls"] += 1
207
+ telem["input_tokens"] += parsed["input_tokens"]
208
+ telem["cached_input_tokens"] += parsed["cache_read_tokens"]
209
+ telem["cache_write_tokens"] += parsed["cache_write_tokens"]
210
+ telem["output_tokens"] += parsed["output_tokens"]
211
+ telem["estimated_cost_usd"] = round(float(telem["estimated_cost_usd"]) + actual, 6)
212
+ telem["estimated_savings_vs_uncached_reasoning_usd"] = round(float(telem["estimated_savings_vs_uncached_reasoning_usd"]) + vs_base, 6)
213
+ tb = by_tier.setdefault(tier, {"calls": 0, "input_tokens": 0, "cached_tokens": 0, "output_tokens": 0})
214
+ tb["calls"] += 1
215
+ tb["input_tokens"] += parsed["input_tokens"]
216
+ tb["cached_tokens"] += parsed["cache_read_tokens"]
217
+ tb["output_tokens"] += parsed["output_tokens"]
218
+ st["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
219
+ atomic_write_json(sf, st)
220
+ except Exception:
221
+ pass
222
+
223
+
224
+ class LLMAdapter:
225
+ """Provider-aware LiteLLM adapter with cache breakpoints, fallback models & escalation."""
226
+
227
+ def __init__(self, litellm_module: Optional[Any] = None) -> None:
228
+ if litellm_module is not None:
229
+ self.litellm = litellm_module
230
+ else:
231
+ try:
232
+ import litellm # type: ignore[import-not-found]
233
+ except ImportError as e:
234
+ raise RuntimeError("Install optional dependency: pip install litellm") from e
235
+ self.litellm = litellm
236
+
237
+ def resolve_models(self, alias: str) -> Tuple[str, Optional[str]]:
238
+ ev = ENV_BY_ALIAS.get(alias, "")
239
+ model = os.getenv(ev, "") if ev else ""
240
+ if not model:
241
+ raise RuntimeError(f"Configure environment variable {ev or alias} for alias '{alias}'.")
242
+ return model, (os.getenv(FALLBACK_ENV_BY_ALIAS.get(alias, ""), "") or None)
243
+
244
+ def complete(
245
+ self,
246
+ alias: str,
247
+ stable_prefix: str,
248
+ dynamic_context: str,
249
+ user_task: str,
250
+ *,
251
+ project_prefix: str = "",
252
+ cache_ttl: str = "5m",
253
+ strict_cache_lint: bool = False,
254
+ repo: Optional[Path] = None,
255
+ prefix_name: str = "default",
256
+ **kwargs: Any,
257
+ ) -> Dict[str, Any]:
258
+ primary, fallback = self.resolve_models(alias)
259
+ candidates = [primary] + ([fallback] if fallback and fallback != primary else [])
260
+ last_err: Optional[Exception] = None
261
+
262
+ for idx, model in enumerate(candidates):
263
+ req = prepare_request(model, stable_prefix, dynamic_context, user_task, project_prefix=project_prefix, cache_ttl=cache_ttl, strict_cache_lint=strict_cache_lint)
264
+ try:
265
+ resp = self.litellm.completion(model=model, messages=req["messages"], **{**req["extra_kwargs"], **kwargs})
266
+ except Exception as err:
267
+ last_err = err
268
+ if idx + 1 < len(candidates):
269
+ continue
270
+ raise
271
+
272
+ usage_raw = _usage_to_dict(getattr(resp, "usage", None))
273
+ parsed = parse_provider_usage(usage_raw, provider=req["provider"])
274
+ if repo is not None:
275
+ ttl_sec = 3600 if cache_ttl == "1h" else PROVIDER_DEFAULTS.get(req["provider"], PROVIDER_DEFAULTS["litellm"])["default_ttl_seconds"]
276
+ _persist_cache_telemetry(Path(repo), prefix_name, req["prefix_id"], req["provider"], model, alias, parsed, ttl_seconds=ttl_sec, cache_ttl=cache_ttl)
277
+
278
+ cache_status = (
279
+ f"verified_cache_hit ({parsed['cache_hit_rate_pct']}% read)" if parsed["cache_verified"] and parsed["cache_read_tokens"] > 0
280
+ else (f"verified_cache_write ({parsed['cache_write_tokens']} tok)" if parsed["cache_verified"] and parsed["cache_write_tokens"] > 0
281
+ else ("verified_cache_miss" if parsed["cache_verified"] else "unverified (provider did not return cache token metadata)"))
282
+ )
283
+ return {
284
+ "model": model, "alias": alias, "used_fallback": idx > 0, "provider": req["provider"],
285
+ "prefix_id": req["prefix_id"], "content": resp.choices[0].message.content,
286
+ "usage": usage_raw, "normalized_usage": parsed, "cache_status": cache_status, "lint_warnings": req["lint_warnings"],
287
+ }
288
+ assert last_err is not None
289
+ raise last_err
290
+
291
+ def complete_with_escalation(
292
+ self, start_alias: str, stable_prefix: str, dynamic_context: str, user_task: str, validator: Any, *, max_escalations: int = 2, **kwargs: Any
293
+ ) -> Dict[str, Any]:
294
+ max_esc = max(0, int(max_escalations))
295
+ idx = ALIAS_ESCALATION_CHAIN.index(start_alias) if start_alias in ALIAS_ESCALATION_CHAIN else 1
296
+ attempts: List[Dict[str, Any]] = []
297
+ for step in range(max_esc + 1):
298
+ cur = ALIAS_ESCALATION_CHAIN[min(len(ALIAS_ESCALATION_CHAIN) - 1, idx + step)]
299
+ res = self.complete(cur, stable_prefix, dynamic_context, user_task, **kwargs)
300
+ ok = bool(validator(res["content"]))
301
+ attempts.append({"alias": cur, "model": res["model"], "passed": ok})
302
+ if ok or cur == ALIAS_ESCALATION_CHAIN[-1] or step == max_esc:
303
+ res["escalation_attempts"] = attempts
304
+ res["validation_passed"] = ok
305
+ return res
306
+ raise RuntimeError("Escalation loop terminated unexpectedly.")