The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): moa_loop — extract fan-out/guidance/cache-plan phases, unify cache-opt and placeholder helpers
Tekniumb10179a1ac42
diff --git a/agent/moa_loop.py b/agent/moa_loop.pyindex 7b4944913d2..631e726cf74 100644--- a/agent/moa_loop.py+++ b/agent/moa_loop.py@@ -25,10 +25,10 @@ from agent.usage_pricing import CanonicalUsagelogger = logging.getLogger(__name__)-# Privacy filter (moa.privacy_filter: '' | display | full, #59959). Secret shapes-# are handled by agent.redact; these two patterns add the PII classes it leaves-# alone (emails, formatted NA phones). The phone pattern requires explicit-# delimiters so line numbers, dates, times, SHAs, IPs and versions never match.+# Privacy filter (moa.privacy_filter: '' | display | full). Secret shapes are handled+# by agent.redact; these add the PII classes it leaves alone (emails, formatted NA+# phones). The phone pattern requires explicit delimiters so line numbers, dates,+# times, SHAs, IPs and versions never match._MOA_EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")_MOA_PHONE_RE = re.compile(r"(?<![\w.+-])" # no leading word char / dot / + / - (kills IPs, IDs, versions)@@ -52,12 +52,11 @@ def _redact_reference_text(text: Any) -> Any:text = redact_sensitive_text(text, force=True, code_file=True)text = _MOA_EMAIL_RE.sub("[redacted email]", text)- text = _MOA_PHONE_RE.sub("[redacted phone]", text)- return text+ return _MOA_PHONE_RE.sub("[redacted phone]", text)def _moa_privacy_mode(moa_raw: Any) -> str:- """Resolve the normalized privacy-filter mode from a raw ``moa`` config."""+ """Normalized privacy-filter mode from a raw ``moa`` config."""from hermes_cli.moa_config import coerce_privacy_filterraw = moa_raw if isinstance(moa_raw, dict) else {}@@ -68,10 +67,7 @@ def _redact_reference_outputs(reference_outputs: list[tuple[str, str, Any]],) -> list[tuple[str, str, Any]]:"""Redact advisor text in reference-output tuples; accounting slot untouched."""- return [- (label, _redact_reference_text(text), acct)- for label, text, acct in reference_outputs- ]+ return [(label, _redact_reference_text(text), acct) for label, text, acct in reference_outputs]def _redact_message_content(content: Any) -> Any:@@ -109,8 +105,8 @@ def _redact_trace_accounting(acct: Any) -> Any:)-# Cold-start caches (#66793): the preset and each (provider, model) runtime are-# immutable for a turn, so avoid re-resolving them on every create() call.+# Cold-start caches: the preset and each (provider, model) runtime are immutable+# for a turn, so avoid re-resolving them on every create() call._preset_cache_lock = threading.Lock()_preset_cache: dict[tuple, Any] = {}@@ -142,6 +138,7 @@ def _resolve_preset_cached(preset_name: str) -> tuple[dict[str, Any], Any]:_preset_cache[key] = presetreturn preset, moa_raw+_runtime_cache_lock = threading.Lock()_runtime_cache: dict[tuple[str, str], tuple[float, dict[str, Any]]] = {}@@ -157,9 +154,9 @@ class _RefAccounting:"""Per-reference usage, cost and full trace (third slot of a reference-output tuple).Advisors may run on a different model than the aggregator, so cost is priced at- the advisor's OWN rate and summed in dollars. ``messages``/``output``/``model``/- ``provider``/``temperature`` carry the full input/output for trace persistence- (only populated when tracing is on).+ the advisor's OWN rate and summed in dollars. The trace fields (``messages``,+ ``output``, ``model``, ``provider``, ``temperature``) are only populated when+ tracing is on."""usage: Any@@ -212,7 +209,6 @@ _REFERENCE_SYSTEM_PROMPT = ()-def _slot_label(slot: dict[str, Any]) -> str:label = f"{(slot.get('provider') or '').strip()}:{(slot.get('model') or '').strip()}"effort = str(slot.get("reasoning_effort") or "").strip()@@ -226,7 +222,7 @@ def _slot_reasoning_config(slot: dict[str, Any]) -> dict[str, Any] | None:from hermes_constants import parse_reasoning_effortreturn parse_reasoning_effort(effort)- except Exception: # pragma: no cover - defensive; bad config must not break MoA+ except Exception: # pragma: no cover - bad config must not break MoAreturn None@@ -234,8 +230,8 @@ def _aggregator_reasoning_config(aggregator: dict[str, Any]) -> dict[str, Any] |"""Resolve the aggregator's reasoning config: slot > per-model > global.The aggregator is the ACTING model, so it falls back through the shared- ``resolve_reasoning_config`` chokepoint (#64187). References deliberately do- not: inheriting a global ``xhigh`` into every advisor would multiply cost.+ ``resolve_reasoning_config`` chokepoint. References deliberately do not:+ inheriting a global ``xhigh`` into every advisor would multiply cost."""cfg = _slot_reasoning_config(aggregator)if cfg is not None:@@ -244,10 +240,8 @@ def _aggregator_reasoning_config(aggregator: dict[str, Any]) -> dict[str, Any] |from hermes_cli.config import load_configfrom hermes_constants import resolve_reasoning_config- return resolve_reasoning_config(- load_config() or {}, str(aggregator.get("model") or "")- )- except Exception: # pragma: no cover - defensive; bad config must not break MoA+ return resolve_reasoning_config(load_config() or {}, str(aggregator.get("model") or ""))+ except Exception: # pragma: no cover - bad config must not break MoAreturn None@@ -256,7 +250,8 @@ def _slot_runtime(slot: dict[str, Any]) -> dict[str, Any]:Gives the slot its provider's real api_mode/base_url/api_key instead of lettingthe auxiliary auto-detector guess. Falls back to bare provider/model on error- (uncached). Cached per (provider, model) with a short TTL (#66793).+ (never cached: a transient error would pin bare kwargs for a TTL). Cached per+ (provider, model) with a short TTL."""provider = str(slot.get("provider") or "").strip()model = str(slot.get("model") or "").strip()@@ -264,10 +259,8 @@ def _slot_runtime(slot: dict[str, Any]) -> dict[str, Any]:now = time.monotonic()with _runtime_cache_lock:entry = _runtime_cache.get(cache_key)- if entry is not None:- stamped_at, cached = entry- if now - stamped_at < _RUNTIME_CACHE_TTL_SECONDS:- return cached+ if entry is not None and now - entry[0] < _RUNTIME_CACHE_TTL_SECONDS:+ return entry[1]out: dict[str, Any] = {"provider": provider, "model": model}try:from hermes_cli.runtime_provider import resolve_runtime_provider@@ -280,20 +273,15 @@ def _slot_runtime(slot: dict[str, Any]) -> dict[str, Any]:if isinstance(extra_body, dict) and extra_body:out["extra_body"] = dict(extra_body)except Exception as exc: # pragma: no cover - defensive- logger.debug("MoA slot runtime resolution failed for %s: %s",- _slot_label(slot), exc)- # Never cache a fallback result: a transient error would pin bare kwargs for a TTL.+ logger.debug("MoA slot runtime resolution failed for %s: %s", _slot_label(slot), exc)return outwith _runtime_cache_lock:_runtime_cache[cache_key] = (now, out)return out-def _merge_slot_extra_body(- slot_extra_body: Any,- caller_extra_body: Any,-) -> Any:- """Merge slot defaults with a caller override for ``call_llm``."""+def _merge_slot_extra_body(slot_extra_body: Any, caller_extra_body: Any) -> Any:+ """Merge slot defaults with a caller override (caller wins) for ``call_llm``."""if isinstance(slot_extra_body, dict) and slot_extra_body:if isinstance(caller_extra_body, dict):return {**slot_extra_body, **caller_extra_body}@@ -303,6 +291,20 @@ def _merge_slot_extra_body(return caller_extra_body+def _agent_cache_opts(agent: Any) -> tuple[Any, Any]:+ """The live agent's ``(_cache_disabled, _cache_ttl)``; ``(None, None)`` without an agent."""+ if agent is None:+ return None, None+ return getattr(agent, "_cache_disabled", None), getattr(agent, "_cache_ttl", None)+++def _with_cache_disabled(runtime: dict[str, Any], cache_disabled: Any) -> dict[str, Any]:+ """Pin the live agent's cache disable onto a runtime snapshot (None is a no-op)."""+ if cache_disabled is None:+ return runtime+ return {**runtime, "_cache_disabled": cache_disabled}++def _maybe_apply_moa_cache_control(messages: list[dict[str, Any]],runtime: dict[str, Any],@@ -314,9 +316,9 @@ def _maybe_apply_moa_cache_control(Same policy function and marker helper as the main loop; MoA has no staticprefix so the legacy system-and-3 fallback is used. ``cache_disabled`` is- stamped onto the stub so ``cache_ttl: off`` is honored (#76085); ``cache_ttl``- threads the agent's tier, clamped per destination (#84733). Returns the- messages unchanged on any error.+ stamped onto the stub so ``cache_ttl: off`` is honored; ``cache_ttl`` threads+ the agent's tier, clamped per destination. Returns the messages unchanged on+ any error."""try:from agent.agent_runtime_helpers import (@@ -332,30 +334,26 @@ def _maybe_apply_moa_cache_control(# Explicit kwarg > runtime snapshot (threaded from the live agent) > config.if cache_disabled is None and "_cache_disabled" in runtime:cache_disabled = runtime.get("_cache_disabled")-- # blank_cache_policy_stub is the only sanctioned stub (carries _cache_disabled, #76085).- stub = blank_cache_policy_stub(cache_disabled)+ provider = runtime.get("provider") or ""+ model = runtime.get("model") or ""+ # blank_cache_policy_stub is the only sanctioned stub (carries _cache_disabled).should_cache, native_layout = anthropic_prompt_cache_policy(- stub,- provider=runtime.get("provider") or "",+ blank_cache_policy_stub(cache_disabled),+ provider=provider,base_url=runtime.get("base_url") or "",api_mode=runtime.get("api_mode") or "",- model=runtime.get("model") or "",+ model=model,)if not should_cache:return messagesreturn apply_anthropic_cache_control(messages,- cache_ttl=effective_cache_ttl(- # None → "5m"; cache-disabled routes already returned above.- cache_ttl,- provider=runtime.get("provider") or "",- model=runtime.get("model") or "",- ),+ # None → "5m"; cache-disabled routes already returned above.+ cache_ttl=effective_cache_ttl(cache_ttl, provider=provider, model=model),native_anthropic=native_layout,- # Envelope routes reject part-level markers in tool_result.content[] (#89886).+ # Envelope routes reject part-level markers in tool_result.content[].tool_part_markers=envelope_tool_part_cache_markers_supported(- runtime.get("provider") or "", runtime.get("base_url") or ""+ provider, runtime.get("base_url") or ""),)except Exception as exc: # pragma: no cover - decoration must never break a call@@ -366,8 +364,8 @@ def _maybe_apply_moa_cache_control(def _price_reference_response(response: Any, slot: dict[str, Any], runtime: dict[str, Any]) -> tuple[Any, Any, str | None, str | None]:- """Normalize a reference response's usage with the slot's OWN provider/api_mode and- price it at its own rate (hence fan-out cost is summed in dollars). Never raises."""+ """Normalize a reference's usage with the slot's OWN provider/api_mode and price it+ at its own rate (hence fan-out cost is summed in dollars). Never raises."""from agent.usage_pricing import estimate_usage_cost, normalize_usageusage = CanonicalUsage()@@ -406,9 +404,8 @@ def _run_reference("""Call one reference model; return ``(label, text, accounting)``. Never raises.The slot is resolved to its provider's real runtime and called through the- same ``call_llm`` path any model uses. Usage is normalized with the slot's OWN- provider/api_mode and priced at its own rate. A failed reference becomes a- labelled ``[failed: …]`` note. Runs inside a thread pool (call_llm is blocking).+ same ``call_llm`` path any model uses. A failed reference becomes a labelled+ ``[failed: …]`` note. Runs inside a thread pool (call_llm is blocking)."""label = _slot_label(slot)runtime = _slot_runtime(slot)@@ -417,12 +414,12 @@ def _run_reference("provider": runtime.get("provider") or slot.get("provider"),"temperature": temperature,}+ # The trimmed view already stripped the agent's system prompt; this is the only one.+ messages = [{"role": "system", "content": _REFERENCE_SYSTEM_PROMPT}, *ref_messages]try:- # The trimmed view already stripped the agent's system prompt; this is the only one.- messages = [{"role": "system", "content": _REFERENCE_SYSTEM_PROMPT}, *ref_messages]- # Trim to THIS model's window (advisors may be smaller than the aggregator, #60345);+ # Trim to THIS model's window (advisors may be smaller than the aggregator);# estimated after the system prompt is prepended so it counts too.- messages = _trim_messages_for_reference(+ trimmed = _trim_messages_for_reference(messages,slot,runtime,@@ -431,52 +428,43 @@ def _run_reference()# Anthropic-style caching is opt-in per request; the advisory view is append-only# across iterations, so decorating lets iteration N+1 replay N's cached prefix.- # Pin the live agent disable onto the runtime (not a fresh config read, #76085).- cache_runtime = runtime- if cache_disabled is not None:- cache_runtime = {**runtime, "_cache_disabled": cache_disabled}- messages = _maybe_apply_moa_cache_control(- messages, cache_runtime, cache_ttl=cache_ttl+ # The live agent disable is pinned onto the runtime (not a fresh config read).+ trimmed = _maybe_apply_moa_cache_control(+ trimmed, _with_cache_disabled(runtime, cache_disabled), cache_ttl=cache_ttl)# Per-slot max_tokens beats the preset-level reference_max_tokens.- _slot_max_tokens: int | None = slot.get("max_tokens")- _effective_max_tokens = _slot_max_tokens if _slot_max_tokens is not None else max_tokens+ slot_max_tokens = slot.get("max_tokens")extra_headers = None# Normalize provider aliases (github, github-copilot, ...) via the canonical table.from agent.auxiliary_client import _normalize_aux_provider- if _normalize_aux_provider(str(runtime.get("provider") or "")) in (- "copilot",- "copilot-acp",- ):+ if _normalize_aux_provider(str(runtime.get("provider") or "")) in ("copilot", "copilot-acp"):# Copilot gates premium models on request attribution; MoA fan-out serves the# user's current turn, so mirror the main agent's x-initiator header.extra_headers = {"x-initiator": "user"}response = call_llm(task="moa_reference",- messages=messages,+ messages=trimmed,temperature=temperature,- max_tokens=_effective_max_tokens,+ max_tokens=slot_max_tokens if slot_max_tokens is not None else max_tokens,timeout=reference_timeout,reasoning_config=_slot_reasoning_config(slot),extra_headers=extra_headers,**runtime,)- _output_text = _extract_text(response) or "(empty response)"+ output_text = _extract_text(response) or "(empty response)"acct = _RefAccounting(*_price_reference_response(response, slot, runtime),- messages=messages,- output=_output_text,+ messages=trimmed,+ output=output_text,**trace_fields,)- return label, _output_text, acct+ return label, output_text, acctexcept Exception as exc:logger.warning("MoA reference model %s failed: %s", label, exc)- return label, f"[failed: {exc}]", _RefAccounting(- CanonicalUsage(),- messages=[{"role": "system", "content": _REFERENCE_SYSTEM_PROMPT}, *ref_messages],- output=f"[failed: {exc}]",- **trace_fields,+ note = f"[failed: {exc}]"+ return label, note, _RefAccounting(+ CanonicalUsage(), messages=messages, output=note, **trace_fields,)@@ -495,7 +483,7 @@ def _trim_messages_for_reference(reserve_output_tokens: int | None = None,context_length_cache: Any = None,) -> list[dict[str, Any]]:- """Trim an advisory request to fit a reference model's context window (#60345).+ """Trim an advisory request to fit a reference model's context window.``messages`` is the full request (advisory system prompt included). Budget =window minus ``reserve_output_tokens`` (or a default) minus a safety fraction.@@ -518,8 +506,8 @@ def _trim_messages_for_reference(return messagescache_key = (provider, model)- context_length: int | None = None- if isinstance(context_length_cache, dict) and cache_key in context_length_cache:+ has_cache = isinstance(context_length_cache, dict)+ if has_cache and cache_key in context_length_cache:context_length = context_length_cache[cache_key]else:try:@@ -530,12 +518,9 @@ def _trim_messages_for_reference(provider=provider,)except Exception:- logger.debug(- "MoA reference context-length resolution failed for %s",- _slot_label(slot),- )+ logger.debug("MoA reference context-length resolution failed for %s", _slot_label(slot))context_length = None- if isinstance(context_length_cache, dict):+ if has_cache:# Cache failures too so a flaky metadata source is not re-probed per reference.context_length_cache[cache_key] = context_length@@ -555,7 +540,7 @@ def _trim_messages_for_reference(if estimated <= budget:return messages- has_system = bool(messages) and messages[0].get("role") == "system"+ has_system = messages[0].get("role") == "system"head = [messages[0]] if has_system else []body = list(messages[1:] if has_system else messages)@@ -575,12 +560,7 @@ def _trim_messages_for_reference(logger.info("MoA reference %s: estimated %d tokens exceeds budget %d ""(window %d, output reserve %d); dropped %d oldest message(s).",- _slot_label(slot),- estimated,- budget,- context_length,- reserve,- dropped,+ _slot_label(slot), estimated, budget, context_length, reserve, dropped,)return trimmed@@ -591,6 +571,47 @@ _REFERENCE_POLL_INTERVAL_S = 5.0_INTERRUPTED_REFERENCE_NOTE = "[skipped: interrupted by user]"+def _placeholder_output(slot: dict[str, Any], note: str) -> tuple[str, str, Any]:+ """A reference-output tuple for a slot that was not (fully) run: zero accounting."""+ return _slot_label(slot), note, _RefAccounting(CanonicalUsage())+++def _settle_interrupted(+ futures: dict[Any, int],+ results: list,+ reference_models: list[dict[str, Any]],+ late_accounting_sink: Any,+) -> None:+ """Fill every unfinished slot after a user interrupt.++ Never-dispatched futures are cancelled (nothing billed). Ones that finished+ between the interrupt check and now keep their real output. Running ones cannot+ be killed and WILL be billed on completion, so their eventual accounting is+ handed to ``late_accounting_sink``.+ """+ for future, idx in futures.items():+ if results[idx] is not None:+ continue+ slot = reference_models[idx]+ if future.cancel():+ results[idx] = _placeholder_output(slot, _INTERRUPTED_REFERENCE_NOTE)+ elif future.done():+ results[idx] = future.result()+ else:+ results[idx] = _placeholder_output(slot, _INTERRUPTED_REFERENCE_NOTE)+ if late_accounting_sink is not None:+ def _record_late(f: Any, _label: str = results[idx][0]) -> None:+ try:+ _lbl, _txt, _acct = f.result()+ except Exception: # pragma: no cover - defensive+ return+ try:+ late_accounting_sink(_label, _acct)+ except Exception: # pragma: no cover - defensive+ logger.debug("MoA: late accounting sink failed for %s", _label)+ future.add_done_callback(_record_late)++def _run_references_parallel(reference_models: list[dict[str, Any]],ref_messages: list[dict[str, Any]],@@ -617,29 +638,23 @@ def _run_references_parallel(results: list[tuple[str, str, Any] | None] = [None] * len(reference_models)futures: dict[Any, int] = {}- workers = min(_MAX_REFERENCE_WORKERS, len(reference_models))# Executor threads start with an empty contextvars.Context; propagate the turn's# (approval callbacks + Nous Portal conversation tag) into each worker.from tools.thread_context import propagate_context_to_threadtotal = len(reference_models)completed = 0- executor = ThreadPoolExecutor(max_workers=workers)+ executor = ThreadPoolExecutor(max_workers=min(_MAX_REFERENCE_WORKERS, total))interrupted = False# Shared per-fan-out context-length cache (dict get/set is GIL-atomic).- _ctx_len_cache: dict[tuple[str, str], int | None] = {}- cache_disabled = (- getattr(agent, "_cache_disabled", None) if agent is not None else None- )- # Agent's cache TTL for every advisor request (#84733); clamped in the decorator.- cache_ttl = getattr(agent, "_cache_ttl", None) if agent is not None else None+ ctx_len_cache: dict[tuple[str, str], int | None] = {}+ # Agent's cache disable + TTL for every advisor request; clamped in the decorator.+ cache_disabled, cache_ttl = _agent_cache_opts(agent)try:for idx, slot in enumerate(reference_models):if slot.get("provider") == "moa":- results[idx] = (- _slot_label(slot),- "[skipped: MoA presets cannot recursively reference MoA]",- _RefAccounting(CanonicalUsage()),+ results[idx] = _placeholder_output(+ slot, "[skipped: MoA presets cannot recursively reference MoA]")continuefutures[@@ -650,14 +665,13 @@ def _run_references_parallel(temperature=temperature,max_tokens=max_tokens,reference_timeout=reference_timeout,- context_length_cache=_ctx_len_cache,+ context_length_cache=ctx_len_cache,cache_disabled=cache_disabled,cache_ttl=cache_ttl,)] = idx- # Collect every reference (no early exit except a user interrupt); progress- # callbacks fire per completion.+ # Collect every reference (no early exit except a user interrupt).pending = set(futures)while pending:done, pending = _futures_wait(pending, timeout=_REFERENCE_POLL_INTERVAL_S)@@ -667,8 +681,7 @@ def _run_references_parallel(completed += 1if progress_callback is not None:try:- label = _slot_label(reference_models[idx])- progress_callback(completed, total, label)+ progress_callback(completed, total, _slot_label(reference_models[idx]))except Exception as exc: # pragma: no cover - display must never breaklogger.debug("MoA progress_callback failed: %s", exc)if not pending:@@ -678,42 +691,7 @@ def _run_references_parallel(breakif interrupted:- for future, idx in futures.items():- if results[idx] is not None:- continue- if future.cancel():- # Never dispatched — nothing was billed.- results[idx] = (- _slot_label(reference_models[idx]),- _INTERRUPTED_REFERENCE_NOTE,- _RefAccounting(CanonicalUsage()),- )- elif future.done():- # Finished between the interrupt check and now: keep its real output/accounting.- results[idx] = future.result()- else:- # Already running — cannot be killed; the provider WILL bill when it- # completes, so hand its eventual accounting to the caller's sink.- label = _slot_label(reference_models[idx])- results[idx] = (- label,- _INTERRUPTED_REFERENCE_NOTE,- _RefAccounting(CanonicalUsage()),- )- if late_accounting_sink is not None:- def _record_late(f: Any, _label: str = label) -> None:- try:- _lbl, _txt, _acct = f.result()- except Exception: # pragma: no cover - defensive- return- try:- late_accounting_sink(_label, _acct)- except Exception: # pragma: no cover - defensive- logger.debug(- "MoA: late accounting sink failed for %s",- _label,- )- future.add_done_callback(_record_late)+ _settle_interrupted(futures, results, reference_models, late_accounting_sink)finally:executor.shutdown(wait=not interrupted, cancel_futures=interrupted)@@ -788,8 +766,6 @@ def _reference_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:# yield a byte-identical view (stable advisory prefix for advisor caching).text = flatten_message_text(content)- if role == "system":- continueif role == "user":if not text.strip() and isinstance(content, list) and content:# Structured content with no text (e.g. image-only): an empty user@@ -802,9 +778,7 @@ def _reference_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:last_user_content = textrendered.append({"role": "user", "content": text})elif role == "assistant":- parts: list[str] = []- if text.strip():- parts.append(text.strip())+ parts = [text.strip()] if text.strip() else []calls_text = _render_tool_calls(msg.get("tool_calls"))if calls_text:parts.append(calls_text)@@ -813,14 +787,13 @@ def _reference_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:rendered.append({"role": "assistant", "content": "\n".join(parts)})elif role == "tool":# Fold the tool result into the preceding assistant turn as text.- result_text = _truncate_tool_result(text)- block = f"[tool result: {result_text}]"+ block = f"[tool result: {_truncate_tool_result(text)}]"if rendered and rendered[-1].get("role") == "assistant":rendered[-1]["content"] = rendered[-1]["content"] + "\n" + blockelse:# No assistant turn to attach to (e.g. a leading tool result).rendered.append({"role": "assistant", "content": block})- # Any other role is ignored.+ # system and any other role are ignored.# End on a user turn by appending a synthetic advisory request (Anthropic# rejects trailing assistant prefill); an existing trailing user turn is left as is.@@ -839,14 +812,13 @@ def _reference_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:return rendered-def _extract_text(response: Any) -> str:+ """Assistant text of a completed response: transport-normalized, else ``choices[0]``."""try:transport = get_transport("chat_completions")if transport is None:raise RuntimeError("chat_completions transport unavailable")- normalized = transport.normalize_response(response)- text = (normalized.content or "").strip()+ text = (transport.normalize_response(response).content or "").strip()if text:return textexcept Exception:@@ -862,10 +834,7 @@ def _extract_text(response: Any) -> str:def _preset_temperature(preset: dict[str, Any], key: str) -> float | None:- """Read an optional preset temperature; None (absent/empty/null) = provider default.-- A hardcoded fallback previously forced 0.6/0.4 even when unset.- """+ """Read an optional preset temperature; None (absent/empty/null) = provider default."""value = preset.get(key)if value is None or (isinstance(value, str) and not value.strip()):return None@@ -884,21 +853,16 @@ def _hash_messages(msgs: list[dict[str, Any]]) -> str:def _is_failed_reference(text: str) -> bool:"""Whether a reference output is a ``[failed: …]`` / ``[skipped: …]`` sentinel."""- sentinel = text.lstrip().lower()- return sentinel.startswith("[failed:") or sentinel.startswith("[skipped:")+ return text.lstrip().lower().startswith(("[failed:", "[skipped:"))-def _successful_references(+def _split_references(reference_outputs: list[tuple[str, str, Any]],-) -> list[tuple[str, str, Any]]:- """Filter failed advice while preserving each accounting payload."""- return [output for output in reference_outputs if not _is_failed_reference(output[1])]---def _failed_reference_labels(- reference_outputs: list[tuple[str, str, Any]],-) -> list[str]:- return [label for label, text, _accounting in reference_outputs if _is_failed_reference(text)]+) -> tuple[list[tuple[str, str, Any]], list[str]]:+ """``(successful outputs, failed labels)``; accounting payloads are preserved."""+ successful = [o for o in reference_outputs if not _is_failed_reference(o[1])]+ failed = [label for label, text, _acct in reference_outputs if _is_failed_reference(text)]+ return successful, faileddef _join_reference_outputs(outputs: list[tuple[str, str, Any]], degraded: str = "") -> str:@@ -931,6 +895,10 @@ def _degraded_notice(failed_labels: list[str], policy: str) -> str:return f"[Reference models unavailable: {', '.join(failed_labels)}]"+def _slot_labels(slots: list[dict[str, Any]]) -> str:+ return ", ".join(_slot_label(slot) for slot in slots)++def aggregate_moa_context(*,user_prompt: str,@@ -948,23 +916,19 @@ def aggregate_moa_context(Failures become model-specific notes instead of aborting the loop.``reference_max_tokens`` caps ONLY the fan-out — capping the aggregator- truncated long syntheses (#53580). ``temperature`` / ``aggregator_temperature``+ truncated long syntheses. ``temperature`` / ``aggregator_temperature``default to None (provider default). ``agent`` makes the fan-out interruptible."""reference_models = [slot for slot in reference_models if slot.get("enabled", True)]- reference_outputs: list[tuple[str, str, Any]] = []- ref_messages = _reference_messages(api_messages)reference_outputs = _run_references_parallel(reference_models,- ref_messages,+ _reference_messages(api_messages),temperature=temperature,max_tokens=reference_max_tokens,reference_timeout=reference_timeout,agent=agent,)-- successful_outputs = _successful_references(reference_outputs)- failed_labels = _failed_reference_labels(reference_outputs)+ successful_outputs, failed_labels = _split_references(reference_outputs)# 'full' privacy mode also redacts advisor text before it reaches this synthesizer# ('display' has no surface here). Failed refs are already filtered out.@@ -986,12 +950,11 @@ def aggregate_moa_context("MoA: all %d reference(s) failed — skipping aggregator synthesis",len(reference_outputs),)- notice = degraded or "[Reference models unavailable]"return ("[Mixture of Agents context — all reference models failed. ""Proceeding without aggregated guidance.]\n"- f"References: {', '.join(_slot_label(slot) for slot in reference_models)}\n\n"- f"{notice}"+ f"References: {_slot_labels(reference_models)}\n\n"+ f"{degraded or '[Reference models unavailable]'}")synth_prompt = (@@ -1006,25 +969,14 @@ def aggregate_moa_context(agg_label = _slot_label(aggregator)agg_runtime = _slot_runtime(aggregator)- # Pin the live agent disable onto synthesis decoration (#76085); None is a no-op.- agg_cache_runtime = agg_runtime- _agg_cache_disabled = (- getattr(agent, "_cache_disabled", None) if agent is not None else None- )- if _agg_cache_disabled is not None:- agg_cache_runtime = {- **agg_runtime,- "_cache_disabled": _agg_cache_disabled,- }- # Agent's cache TTL for the one-shot synthesis path (#84733).- _agg_cache_ttl = getattr(agent, "_cache_ttl", None) if agent is not None else None+ cache_disabled, cache_ttl = _agent_cache_opts(agent)try:# Same cache_control decoration as the advisor calls; this synthesis call is# a third independent MoA call path that otherwise re-bills its full input.agg_messages = _maybe_apply_moa_cache_control([{"role": "user", "content": synth_prompt}],- agg_cache_runtime,- cache_ttl=_agg_cache_ttl,+ _with_cache_disabled(agg_runtime, cache_disabled),+ cache_ttl=cache_ttl,)response = call_llm(task="moa_aggregator",@@ -1038,16 +990,13 @@ def aggregate_moa_context(logger.warning("MoA aggregator model %s failed: %s", agg_label, exc)synthesis = ""- if not synthesis:- synthesis = joined-return ("[Mixture of Agents context — use this as private guidance for the ""normal Hermes agent loop. You may call tools, continue reasoning, or ""finish normally.]\n"f"Aggregator: {agg_label}\n"- f"References: {', '.join(_slot_label(slot) for slot in reference_models)}\n\n"- f"{synthesis.strip()}"+ f"References: {_slot_labels(reference_models)}\n\n"+ f"{(synthesis or joined).strip()}")@@ -1056,25 +1005,24 @@ def _completed_response_as_stream_chunk(response: Any) -> Any:Done at the MoA facade boundary so transports stay untouched."""-choices = getattr(response, "choices", None)first_choice = choices[0] if isinstance(choices, (list, tuple)) and choices else Nonemessage = getattr(first_choice, "message", None)raw_tool_calls = getattr(message, "tool_calls", None)tool_call_deltas = Noneif isinstance(raw_tool_calls, (list, tuple)) and raw_tool_calls:- tool_call_deltas = []- for index, tc in enumerate(raw_tool_calls):- function = getattr(tc, "function", None)- tool_call_deltas.append(SimpleNamespace(+ tool_call_deltas = [+ SimpleNamespace(index=getattr(tc, "index", index),id=getattr(tc, "id", None),type=getattr(tc, "type", None) or "function",function=SimpleNamespace(- name=getattr(function, "name", None),- arguments=getattr(function, "arguments", None),+ name=getattr(getattr(tc, "function", None), "name", None),+ arguments=getattr(getattr(tc, "function", None), "arguments", None),),- ))+ )+ for index, tc in enumerate(raw_tool_calls)+ ]delta = SimpleNamespace(content=getattr(message, "content", None),tool_calls=tool_call_deltas,@@ -1124,7 +1072,7 @@ def peel_reference_guidance("""Exact inverse of ``_attach_reference_guidance`` (the three attach shapes).Used by the failover redecoration chokepoint so a cache breakpoint never lands- on the turn-varying guidance (#72626). Returns a new list; inputs are not mutated.+ on the turn-varying guidance. Returns a new list; inputs are not mutated."""if not guidance or not messages:return messages@@ -1139,42 +1087,37 @@ def peel_reference_guidance(suffix = "\n\n" + guidance_textif isinstance(content, str) and content.endswith(suffix):# Attach shape (a): merged into a trailing string user turn.- peeled = dict(last)- peeled["content"] = content[: -len(suffix)]- return [*messages[:-1], peeled]+ return [*messages[:-1], {**last, "content": content[: -len(suffix)]}]if isinstance(content, list) and content:last_part = content[-1]if isinstance(last_part, dict) and last_part.get("type", "text") == "text":text = last_part.get("text") or ""if text == suffix or text == guidance_text:- # Attach shape (b): guidance rode as its own trailing part.- peeled = dict(last)- peeled["content"] = list(content[:-1])- if not peeled["content"]:- # Guidance was the only content: drop the whole message (mirrors shape c).+ # Attach shape (b): guidance rode as its own trailing part. Guidance as+ # the only content drops the whole message (mirrors shape c).+ if len(content) == 1:return list(messages[:-1])- return [*messages[:-1], peeled]+ return [*messages[:-1], {**last, "content": list(content[:-1])}]if text.endswith(suffix):- new_part = dict(last_part)- new_part["text"] = text[: -len(suffix)]- peeled = dict(last)- peeled["content"] = [*content[:-1], new_part]- return [*messages[:-1], peeled]+ new_part = {**last_part, "text": text[: -len(suffix)]}+ return [*messages[:-1], {**last, "content": [*content[:-1], new_part]}]return messagesclass MoAChatCompletions:- """OpenAI-chat-compatible facade where the aggregator is the acting model."""+ """OpenAI-chat-compatible facade where the aggregator is the acting model.++ ``reference_callback(event, **kwargs)`` is an optional best-effort display hook:+ "moa.reference" index, count, label, text+ "moa.progress" refs_done, refs_total, label (per reference completion)+ "moa.phase" phase, refs_done, refs_total, aggregator+ "moa.aggregating" aggregator (label), ref_count+ ``agent`` is the owning AIAgent; it lets the fan-out check ``_interrupt_requested``.+ """def __init__(self, preset_name: str, reference_callback: Any = None, agent: Any = None):self.preset_name = preset_name or "default"- # Optional best-effort display hook, called as ``reference_callback(event, **kwargs)``:- # "moa.reference" index, count, label, text- # "moa.progress" refs_done, refs_total, label (per reference completion)- # "moa.phase" phase, refs_done, refs_total, aggregator- # "moa.aggregating" aggregator (label), ref_countself.reference_callback = reference_callback- # Owning AIAgent (optional); lets the fan-out check agent._interrupt_requested.self._agent = agent# State-scoped reference cache keyed on the advisory-view signature: a new# user/tool message is a MISS (references re-run), a redundant create() with@@ -1183,9 +1126,9 @@ class MoAChatCompletions:self._ref_cache_outputs: list[tuple[str, str, Any]] = []# Fan-out usage/cost from the latest cache-MISS create(), awaiting# consume_reference_usage (zero deposited on a HIT so spend counts once).+ # The lock guards them against late-accounting callbacks on worker threads.self._pending_reference_usage: Any = CanonicalUsage()self._pending_reference_cost: Any = None- # Guards pending usage/cost against late-accounting callbacks on worker threads.self._accounting_lock = threading.Lock()# Resolved aggregator slot from the latest create(); cost accounting prices the# acting turn at its real model instead of the virtual preset name.@@ -1227,16 +1170,12 @@ class MoAChatCompletions:if not isinstance(accounting, _RefAccounting):returnself._fold_pending_accounting(*_sum_reference_accounting([(label, "", accounting)]))- logger.debug(- "MoA: recorded late accounting for interrupted reference %s", label- )+ logger.debug("MoA: recorded late accounting for interrupted reference %s", label)def _fold_pending_accounting(self, usage: Any, cost: Any) -> None:"""Add (never overwrite) fan-out spend so late interrupted-reference deposits survive."""with self._accounting_lock:- self._pending_reference_usage = (- self._pending_reference_usage or CanonicalUsage()- ) + usage+ self._pending_reference_usage = (self._pending_reference_usage or CanonicalUsage()) + usageif cost is not None:self._pending_reference_cost = (self._pending_reference_cost or 0) + cost@@ -1303,41 +1242,30 @@ class MoAChatCompletions:_attach_reference_guidance(agg_messages, str(guidance))return {**prepared, "messages": agg_messages}- def _call_prepared_aggregator(- self, prepared: dict[str, Any], api_kwargs: dict[str, Any]- ) -> Any:- """Send an already prepared MoA aggregator request exactly once."""- agg_messages = prepared["messages"]- aggregator = prepared["aggregator"]- aggregator_temperature = prepared["aggregator_temperature"]- if aggregator.get("provider") == "moa":- raise RuntimeError("MoA aggregator cannot be another MoA preset")- agg_kwargs = dict(api_kwargs)- max_tokens: Any = agg_kwargs.get("max_tokens")- tools: Any = agg_kwargs.get("tools")- extra_body: Any = agg_kwargs.get("extra_body")- agg_runtime = _slot_runtime(aggregator)+ def _plan_aggregator_cache(+ self,+ agg_messages: list[dict[str, Any]],+ tools: Any,+ guidance: Any,+ agg_runtime: dict[str, Any],+ ) -> tuple[list[dict[str, Any]], Any]:+ """Decorate the aggregator request with cache breakpoints for its destination.++ The guidance is peeled before planning and re-attached after so a breakpoint+ never lands on the turn-varying block. On any error the undecorated request+ is returned (warning, not debug: this is the aggregator's ONLY decoration path).+ """try:- from agent.agent_runtime_helpers import (- plan_cache_sections_for_destination,- )+ from agent.agent_runtime_helpers import plan_cache_sections_for_destination- guidance = prepared.get("guidance")planning_messages = agg_messagesif guidance:- planning_messages = peel_reference_guidance(- agg_messages,- str(guidance),- )+ planning_messages = peel_reference_guidance(agg_messages, str(guidance))# plan_cache_sections_for_destination returns request-local copies.# Tri-state cache_disabled: facades built via __new__ have no _agent; forcing- # False would suppress the planner's config fallback (#76085).+ # False would suppress the planner's config fallback._agent = getattr(self, "_agent", None)- _cache_disabled = (- getattr(_agent, "_cache_disabled", None)- if _agent is not None- else None- )+ cache_disabled, cache_ttl = _agent_cache_opts(_agent)agg_messages, tools = plan_cache_sections_for_destination(planning_messages,tools,@@ -1345,21 +1273,31 @@ class MoAChatCompletions:base_url=agg_runtime.get("base_url") or "",api_mode=agg_runtime.get("api_mode") or "",model=agg_runtime.get("model") or "",- cache_disabled=_cache_disabled,- # Agent TTL + stable system prefix so MoA stops regressing 1h → 5m (#84733).- cache_ttl=getattr(_agent, "_cache_ttl", None),- static_system_prefix=getattr(- _agent, "_cached_system_prompt_static", None- ),+ cache_disabled=cache_disabled,+ # Agent TTL + stable system prefix so MoA does not regress 1h → 5m.+ cache_ttl=cache_ttl,+ static_system_prefix=getattr(_agent, "_cached_system_prompt_static", None),)if guidance:_attach_reference_guidance(agg_messages, str(guidance))except Exception as exc: # pragma: no cover - cache planning must not block MoA- # Warning, not debug: this is the aggregator's ONLY decoration path.logger.warning("MoA aggregator cache plan failed — sending undecorated ""request (cache misses expected): %s", exc,)+ return agg_messages, tools++ def _call_prepared_aggregator(+ self, prepared: dict[str, Any], api_kwargs: dict[str, Any]+ ) -> Any:+ """Send an already prepared MoA aggregator request exactly once."""+ aggregator = prepared["aggregator"]+ if aggregator.get("provider") == "moa":+ raise RuntimeError("MoA aggregator cannot be another MoA preset")+ agg_runtime = _slot_runtime(aggregator)+ agg_messages, tools = self._plan_aggregator_cache(+ prepared["messages"], api_kwargs.get("tools"), prepared.get("guidance"), agg_runtime+ )# Record the exact aggregator INPUT into the pending trace; the persisted COPY# is redacted under any privacy mode while the live input stays raw.if self._pending_trace is not None:@@ -1377,26 +1315,23 @@ class MoAChatCompletions:stream_kwargs: dict[str, Any] = {}if stream:stream_kwargs["stream"] = True- stream_kwargs["stream_options"] = (- api_kwargs.get("stream_options") or {"include_usage": True}- )+ stream_kwargs["stream_options"] = api_kwargs.get("stream_options") or {"include_usage": True}# The consumer's stream-read timeout must govern the aggregator stream.if api_kwargs.get("timeout") is not None:stream_kwargs["timeout"] = api_kwargs["timeout"]# Pop the runtime's extra_body and merge with the caller's (caller wins) so the# explicit kwarg never collides with **agg_runtime.agg_extra_body = _merge_slot_extra_body(- agg_runtime.pop("extra_body", None),- extra_body,+ agg_runtime.pop("extra_body", None), api_kwargs.get("extra_body"),)- _agg_response = call_llm(+ agg_response = call_llm(task="moa_aggregator",messages=agg_messages,- temperature=aggregator_temperature,- max_tokens=max_tokens,+ temperature=prepared["aggregator_temperature"],+ max_tokens=api_kwargs.get("max_tokens"),tools=tools,extra_body=agg_extra_body,- # Same reasoning policy as the direct create() path (#64187).+ # Same reasoning policy as the direct create() path.reasoning_config=_aggregator_reasoning_config(aggregator),**stream_kwargs,**agg_runtime,@@ -1404,20 +1339,19 @@ class MoAChatCompletions:# Non-streaming: capture the aggregator output inline. Streaming: the output# lands as the turn's assistant message; the trace marks it streamed.if self._pending_trace is not None:- if stream:- self._pending_trace["aggregator_streamed"] = True- self._pending_trace["aggregator_output"] = None- else:- self._pending_trace["aggregator_streamed"] = False+ self._pending_trace["aggregator_streamed"] = stream+ output = None+ if not stream:try:- self._pending_trace["aggregator_output"] = _extract_text(_agg_response)+ output = _extract_text(agg_response)except Exception: # pragma: no cover - defensive- self._pending_trace["aggregator_output"] = None- if stream and hasattr(_agg_response, "choices"):+ output = None+ self._pending_trace["aggregator_output"] = output+ if stream and hasattr(agg_response, "choices"):# Some adapters (openai-codex Responses) return a completed response even- # when streaming was requested; hand the loop a one-chunk iterator (#55933).- return iter((_completed_response_as_stream_chunk(_agg_response),))- return _agg_response+ # when streaming was requested; hand the loop a one-chunk iterator.+ return iter((_completed_response_as_stream_chunk(agg_response),))+ return agg_responsedef _fanout_cache_key(self,@@ -1427,12 +1361,12 @@ class MoAChatCompletions:) -> tuple:"""Compute the turn-scoped reference cache key per the preset's fan-out cadence.- Cadence (#67199, #63393). "user_turn" (default): advisors run once per user- turn — the signature hashes only the prefix up to the LAST USER message, so later- tool iterations are cache HITs. "per_iteration": re-run whenever the advisory- view changes. "every_n:<N>": iteration 1 of a turn, then every Nth; in-between- iterations reuse the last on-cadence guidance (key pinned to that run so the- lookup is a HIT: no advisor calls, no double accounting, no re-emit).+ "user_turn" (default): advisors run once per user turn — the signature hashes+ only the prefix up to the LAST USER message, so later tool iterations are+ cache HITs. "per_iteration": re-run whenever the advisory view changes.+ "every_n:<N>": iteration 1 of a turn, then every Nth; in-between iterations+ reuse the last on-cadence guidance (key pinned to that run so the lookup is a+ HIT: no advisor calls, no double accounting, no re-emit)."""fanout_mode = str(preset.get("fanout") or "user_turn").strip().lower()every_n = 0@@ -1449,10 +1383,10 @@ class MoAChatCompletions:if fanout_mode == "user_turn" or every_n >= 2:# Last REAL user message: the synthetic _ADVISORY_INSTRUCTION marker must not# count or the prefix would grow (and re-sign) every iteration.- for _i in range(len(ref_messages) - 1, -1, -1):- _m = ref_messages[_i]- if _m.get("role") == "user" and _m.get("content") != _ADVISORY_INSTRUCTION:- turn_prefix = ref_messages[: _i + 1]+ for i in range(len(ref_messages) - 1, -1, -1):+ m = ref_messages[i]+ if m.get("role") == "user" and m.get("content") != _ADVISORY_INSTRUCTION:+ turn_prefix = ref_messages[: i + 1]breakif fanout_mode == "user_turn":sig_messages = turn_prefix@@ -1460,18 +1394,18 @@ class MoAChatCompletions:# every_n bookkeeping: advance the counter only when the advisory STATE changed# (a streaming retry must not consume a cadence slot); reset on a new turn prefix.if every_n >= 2:- _turn_sig = _hash_messages(turn_prefix)- if _turn_sig != self._fanout_turn_sig:- self._fanout_turn_sig = _turn_sig+ turn_sig = _hash_messages(turn_prefix)+ if turn_sig != self._fanout_turn_sig:+ self._fanout_turn_sig = turn_sigself._fanout_iteration_count = 0self._fanout_last_state_sig = None- _state_sig = _hash_messages(ref_messages)- if _state_sig != self._fanout_last_state_sig:- self._fanout_last_state_sig = _state_sig+ state_sig = _hash_messages(ref_messages)+ if state_sig != self._fanout_last_state_sig:+ self._fanout_last_state_sig = state_sigself._fanout_iteration_count += 1# Iteration 1 is on-cadence; then every Nth iteration after it.- _on_cadence = (self._fanout_iteration_count - 1) % every_n == 0- if not _on_cadence and self._ref_cache_outputs:+ on_cadence = (self._fanout_iteration_count - 1) % every_n == 0+ if not on_cadence and self._ref_cache_outputs:return self._ref_cache_keyreturn (@@ -1480,154 +1414,109 @@ class MoAChatCompletions:tuple(_slot_label(s) for s in reference_models),)- def create(self, **api_kwargs: Any) -> Any:- prepared_request = api_kwargs.pop("_moa_prepared_request", None)- if prepared_request is not None:- if not isinstance(prepared_request, dict):- raise TypeError("_moa_prepared_request must be a dict")- return self._call_prepared_aggregator(prepared_request, api_kwargs)-- preset, _moa_raw = _resolve_preset_cached(self.preset_name)- # Remembered on self so _call_prepared_aggregator redacts the trace consistently.- privacy_mode = _moa_privacy_mode(_moa_raw)- self._privacy_mode = privacy_mode- messages = list(api_kwargs.get("messages") or [])- reference_models = [- slot for slot in (preset.get("reference_models") or [])- if slot.get("enabled", True)- ]- aggregator = preset.get("aggregator") or {}- # The MoA path's virtual model/provider have no pricing entry; expose the real slot.- self.last_aggregator_slot = dict(aggregator) if aggregator else None+ def _run_fanout(+ self,+ preset: dict[str, Any],+ ref_messages: list[dict[str, Any]],+ reference_models: list[dict[str, Any]],+ aggregator: dict[str, Any],+ aggregator_temperature: Any,+ cache_key: tuple,+ ) -> list[tuple[str, str, Any]]:+ """Cache-MISS path of ``create``: run the advisors, account, trace and emit."""# No output caps by default (None → call_llm omits max_tokens). A preset MAY cap# ADVISOR output (dominant MoA latency); the acting aggregator is never capped.- reference_max_tokens = preset.get("reference_max_tokens")- # None = provider default (see _preset_temperature).- temperature = _preset_temperature(preset, "reference_temperature")- aggregator_temperature = _preset_temperature(preset, "aggregator_temperature")- # None = inherit auxiliary.moa_reference.timeout via call_llm.+ # None reference_timeout = inherit auxiliary.moa_reference.timeout via call_llm.raw_reference_timeout = preset.get("reference_timeout")- reference_timeout = (- float(raw_reference_timeout) if raw_reference_timeout else None- )- degraded_reference_policy = str(- preset.get("degraded_reference_policy") or "loud"- )- if aggregator_temperature is None and api_kwargs.get("temperature") is not None:- # The acting agent's own temperature applies to the aggregator (the acting model).- aggregator_temperature = api_kwargs.get("temperature")-- # A disabled preset = "use the aggregator directly".- if not preset.get("enabled", True):- reference_models = []- reference_outputs: list[tuple[str, str, Any]] = []- ref_messages = _reference_messages(messages)- _cache_key = self._fanout_cache_key(preset, ref_messages, reference_models)- _refs_from_cache = _cache_key == self._ref_cache_key and bool(self._ref_cache_outputs)-- if _refs_from_cache:- reference_outputs = list(self._ref_cache_outputs)- # Cache HIT: references already ran and were accounted this turn. Deposit- # nothing, but do NOT zero pending totals (a late interrupted reference may- # have deposited real spend). No trace either — a repeat iteration is not a turn.- self._pending_trace = None+ def _progress(done: int, total: int, label: str) -> None:+ self._emit("moa.progress", refs_done=done, refs_total=total, label=label)++ reference_outputs = _run_references_parallel(+ reference_models,+ ref_messages,+ temperature=_preset_temperature(preset, "reference_temperature"),+ max_tokens=preset.get("reference_max_tokens"),+ progress_callback=_progress,+ reference_timeout=float(raw_reference_timeout) if raw_reference_timeout else None,+ agent=self._agent,+ late_accounting_sink=self._record_late_reference_accounting,+ )+ if any(text == _INTERRUPTED_REFERENCE_NOTE for _lbl, text, _acct in reference_outputs):+ # An interrupted fan-out is a partial snapshot: never cache it (a HIT+ # would replay placeholder notes every iteration).+ self._ref_cache_key = None+ self._ref_cache_outputs = []else:- # Per-reference progress (``moa.progress``) through the same display hook.- def _progress(done: int, total: int, label: str) -> None:- self._emit(- "moa.progress",- refs_done=done,- refs_total=total,- label=label,- )-- reference_outputs = _run_references_parallel(- reference_models,- ref_messages,- temperature=temperature,- max_tokens=reference_max_tokens,- progress_callback=_progress,- reference_timeout=reference_timeout,- agent=self._agent,- late_accounting_sink=self._record_late_reference_accounting,+ self._ref_cache_key = cache_key+ self._ref_cache_outputs = list(reference_outputs)+ # Fold advisor spend into accounting exactly once per turn.+ self._fold_pending_accounting(*_sum_reference_accounting(reference_outputs))+ # Stash the fan-out for trace persistence (aggregator input/label filled in+ # later; output stitched in by consume_and_save_trace). Traces are persisted,+ # so ANY active privacy mode redacts advisor text and per-advisor input/output.+ privacy_mode = self._privacy_mode+ if privacy_mode:+ trace_refs = [+ (label, _redact_reference_text(text), _redact_trace_accounting(acct))+ for label, text, acct in reference_outputs+ ]+ else:+ trace_refs = list(reference_outputs)+ self._pending_trace = {+ "preset": self.preset_name,+ "reference_outputs": trace_refs,+ "aggregator_slot": aggregator,+ "aggregator_temperature": aggregator_temperature,+ }+ # Derived from the privacy-redacted trace_refs.+ try:+ from agent.moa_trace import slot_metrics++ self._last_reference_metrics = [+ slot_metrics(acct, label, output=text) for label, text, acct in trace_refs+ ]+ except Exception as exc: # pragma: no cover - never break a turn+ logger.debug("MoA reference metrics render failed: %s", exc)+ self._last_reference_metrics = None++ # Surface each reference's answer BEFORE the aggregator acts (once per turn).+ # The cache keeps RAW text; redaction happens at each consuming surface.+ ref_count = len(reference_outputs)+ for idx, (label, text, _accounting) in enumerate(reference_outputs, start=1):+ self._emit(+ "moa.reference",+ index=idx,+ count=ref_count,+ label=label,+ text=_redact_reference_text(text) if privacy_mode else text,)- interrupted_any = any(- text == _INTERRUPTED_REFERENCE_NOTE- for _lbl, text, _acct in reference_outputs+ if ref_count:+ # Phase transition: fan-out complete, aggregator about to act.+ agg_label = _slot_label(aggregator)+ self._emit(+ "moa.phase",+ phase="aggregator",+ refs_done=ref_count,+ refs_total=ref_count,+ aggregator=agg_label,)- if interrupted_any:- # An interrupted fan-out is a partial snapshot: never cache it (a HIT- # would replay placeholder notes every iteration).- self._ref_cache_key = None- self._ref_cache_outputs = []- else:- self._ref_cache_key = _cache_key- self._ref_cache_outputs = list(reference_outputs)- # Fold advisor spend into accounting exactly once per turn.- self._fold_pending_accounting(*_sum_reference_accounting(reference_outputs))- # Stash the fan-out for trace persistence (aggregator input/label filled in- # later; output stitched in by consume_and_save_trace). Traces are persisted,- # so ANY active privacy mode redacts advisor text and per-advisor input/output.- if privacy_mode:- _trace_refs = [- (label, _redact_reference_text(text), _redact_trace_accounting(acct))- for label, text, acct in reference_outputs- ]- else:- _trace_refs = list(reference_outputs)- self._pending_trace = {- "preset": self.preset_name,- "reference_outputs": _trace_refs,- "aggregator_slot": aggregator,- "aggregator_temperature": aggregator_temperature,- }- # Derived from the privacy-redacted _trace_refs.- try:- from agent.moa_trace import slot_metrics-- self._last_reference_metrics = [- slot_metrics(acct, label, output=text)- for label, text, acct in _trace_refs- ]- except Exception as exc: # pragma: no cover - never break a turn- logger.debug("MoA reference metrics render failed: %s", exc)- self._last_reference_metrics = None-- # Surface each reference's answer BEFORE the aggregator acts (once per turn).- # The cache keeps RAW text; redaction happens at each consuming surface.- _ref_count = len(reference_outputs)- for _idx, (_label, _text, _accounting) in enumerate(reference_outputs, start=1):- self._emit(- "moa.reference",- index=_idx,- count=_ref_count,- label=_label,- text=_redact_reference_text(_text) if privacy_mode else _text,- )- if _ref_count:- # Phase transition: fan-out complete, aggregator about to act.- self._emit(- "moa.phase",- phase="aggregator",- refs_done=_ref_count,- refs_total=_ref_count,- aggregator=_slot_label(aggregator),- )- self._emit(- "moa.aggregating",- aggregator=_slot_label(aggregator),- ref_count=_ref_count,- )+ self._emit("moa.aggregating", aggregator=agg_label, ref_count=ref_count)+ return reference_outputs- agg_messages = [dict(m) for m in messages]- successful_outputs = _successful_references(reference_outputs)- failed_labels = _failed_reference_labels(reference_outputs)- # 'full' privacy mode redacts advisor text reaching the AGGREGATOR too (#59959);- # 'display' leaves it raw. Applied to a per-call copy — the cache holds raw text.- _agg_refs = (+ def _build_guidance(+ self,+ reference_outputs: list[tuple[str, str, Any]],+ aggregator: dict[str, Any],+ degraded_reference_policy: str,+ ) -> str | None:+ """Render the reference block attached to the aggregator prompt (None = nothing)."""+ successful_outputs, failed_labels = _split_references(reference_outputs)+ # 'full' privacy mode redacts advisor text reaching the AGGREGATOR too; 'display'+ # leaves it raw. Applied to a per-call copy — the cache holds raw text.+ agg_refs = (_redact_reference_outputs(successful_outputs)- if privacy_mode == "full"+ if self._privacy_mode == "full"else successful_outputs)degraded = _degraded_notice(failed_labels, degraded_reference_policy)@@ -1636,7 +1525,6 @@ class MoAChatCompletions:f"Preset: {self.preset_name}\n"f"Aggregator/acting model: {_slot_label(aggregator)}\n")- guidance: str | None = Noneif reference_outputs and not successful_outputs:# Every reference failed: the aggregator acts alone. Under the loud policy it# still gets the sanitized unavailability notice; under silent, nothing.@@ -1646,20 +1534,65 @@ class MoAChatCompletions:len(reference_outputs),)if degraded:- guidance = (+ return (f"{header}\n""All reference models failed this turn — no advisory ""guidance is available. Act on your own judgment.\n\n"f"{degraded}")- elif _agg_refs or degraded:- guidance = (+ return None+ if agg_refs or degraded:+ return (f"{header}"- f"References: {', '.join(label for label, _, _ in _agg_refs)}\n\n"+ f"References: {', '.join(label for label, _, _ in agg_refs)}\n\n""Use the reference responses below as private context. You are the aggregator and acting model: ""answer the user directly or call tools as needed.\n\n"- f"{_join_reference_outputs(_agg_refs, degraded)}"+ f"{_join_reference_outputs(agg_refs, degraded)}"+ )+ return None++ def create(self, **api_kwargs: Any) -> Any:+ prepared_request = api_kwargs.pop("_moa_prepared_request", None)+ if prepared_request is not None:+ if not isinstance(prepared_request, dict):+ raise TypeError("_moa_prepared_request must be a dict")+ return self._call_prepared_aggregator(prepared_request, api_kwargs)++ preset, moa_raw = _resolve_preset_cached(self.preset_name)+ # Remembered on self so _call_prepared_aggregator redacts the trace consistently.+ self._privacy_mode = _moa_privacy_mode(moa_raw)+ messages = list(api_kwargs.get("messages") or [])+ # A disabled preset = "use the aggregator directly".+ reference_models = [+ slot for slot in (preset.get("reference_models") or [])+ if slot.get("enabled", True)+ ] if preset.get("enabled", True) else []+ aggregator = preset.get("aggregator") or {}+ # The MoA path's virtual model/provider have no pricing entry; expose the real slot.+ self.last_aggregator_slot = dict(aggregator) if aggregator else None+ # None = provider default (see _preset_temperature); the acting agent's own+ # temperature applies to the aggregator (the acting model).+ aggregator_temperature = _preset_temperature(preset, "aggregator_temperature")+ if aggregator_temperature is None and api_kwargs.get("temperature") is not None:+ aggregator_temperature = api_kwargs.get("temperature")++ ref_messages = _reference_messages(messages)+ cache_key = self._fanout_cache_key(preset, ref_messages, reference_models)+ if cache_key == self._ref_cache_key and self._ref_cache_outputs:+ # Cache HIT: references already ran and were accounted this turn. Deposit+ # nothing, but do NOT zero pending totals (a late interrupted reference may+ # have deposited real spend). No trace either — a repeat iteration is not a turn.+ reference_outputs = list(self._ref_cache_outputs)+ self._pending_trace = None+ else:+ reference_outputs = self._run_fanout(+ preset, ref_messages, reference_models, aggregator, aggregator_temperature, cache_key)++ agg_messages = [dict(m) for m in messages]+ guidance = self._build_guidance(+ reference_outputs, aggregator, str(preset.get("degraded_reference_policy") or "loud")+ )if guidance:_attach_reference_guidance(agg_messages, guidance)@@ -1724,8 +1657,8 @@ def build_moa_facade(agent, preset_name: Any = None) -> MoAClient:Single construction point for ``MoAClient`` (agent_init, fallback restore,transport recovery, switch_model): a bare ``MoAClient(preset)`` would drop the- ``reference_callback`` relay and silence display events for the session- (#53802). The relay reads ``agent.tool_progress_callback`` at emit time.+ ``reference_callback`` relay and silence display events for the session.+ The relay reads ``agent.tool_progress_callback`` at emit time."""def _moa_reference_relay(event: str, **kwargs: Any) -> None:cb = getattr(agent, "tool_progress_callback", None)@@ -1760,9 +1693,5 @@ def build_moa_facade(agent, preset_name: Any = None) -> MoAClient:except Exception:resolved_preset = "default"- return MoAClient(- resolved_preset,- reference_callback=_moa_reference_relay,- # Lets the fan-out wait be aborted on a user interrupt.- agent=agent,- )+ # ``agent`` lets the fan-out wait be aborted on a user interrupt.+ return MoAClient(resolved_preset, reference_callback=_moa_reference_relay, agent=agent)