|
| 1 | +# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +"""Merge MAS workflow onto the entry agent manifest at run-mas bootstrap.""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import copy |
| 8 | +import logging |
| 9 | +from collections.abc import Callable |
| 10 | +from pathlib import Path |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +from mas.ctl.manifest.spec_bindings import parse_collaboration |
| 14 | +from mas.runtime.boundary.delegation.llm_delegator import LlmDelegator |
| 15 | +from mas.runtime.boundary.delegation.policy import delegation_targets |
| 16 | +from mas.runtime.engine.llm_live import LiveLlmEngine |
| 17 | +from mas.runtime.engine.tools import resolve_manifest_tool_refs |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | +RunTurnFn = Callable[[str, str], str] |
| 22 | + |
| 23 | + |
| 24 | +def _leaf_engine(engine: Any) -> Any: |
| 25 | + """Unwrap infra pipeline facades to the engine that handles LLM/tool IO.""" |
| 26 | + seen: set[int] = set() |
| 27 | + current = engine |
| 28 | + while current is not None and id(current) not in seen: |
| 29 | + seen.add(id(current)) |
| 30 | + inner = getattr(current, "inner", None) |
| 31 | + if inner is None: |
| 32 | + return current |
| 33 | + current = inner |
| 34 | + return current |
| 35 | + |
| 36 | + |
| 37 | +def enrich_entry_agent_for_delegation( |
| 38 | + agent_manifest: dict[str, Any], |
| 39 | + mas_config: dict[str, Any], |
| 40 | + *, |
| 41 | + manifest_dir: Path | None = None, |
| 42 | +) -> dict[str, Any]: |
| 43 | + """Attach MAS ``workflow`` to the entry agent; resolve tool refs.""" |
| 44 | + spec = agent_manifest.get("spec") or {} |
| 45 | + parse_collaboration(spec.get("collaboration")) |
| 46 | + out = copy.deepcopy(agent_manifest) |
| 47 | + mas_spec = mas_config.get("spec", mas_config) if isinstance(mas_config, dict) else {} |
| 48 | + wf = mas_spec.get("workflow") |
| 49 | + if isinstance(wf, dict): |
| 50 | + spec_out = out.setdefault("spec", {}) |
| 51 | + if spec_out.get("workflow") and spec_out.get("workflow") != wf: |
| 52 | + logger.warning( |
| 53 | + "entry agent spec.workflow replaced by MAS workflow (MAS topology wins)" |
| 54 | + ) |
| 55 | + # wf comes from mas_config (not agent_manifest); copy once to avoid shared refs. |
| 56 | + spec_out["workflow"] = copy.deepcopy(wf) |
| 57 | + if manifest_dir is not None: |
| 58 | + resolve_manifest_tool_refs(out, manifest_dir, inplace=True) |
| 59 | + return out |
| 60 | + |
| 61 | + |
| 62 | +def wire_entry_engine_delegation( |
| 63 | + engine: Any, |
| 64 | + manifest: dict[str, Any], |
| 65 | + manifest_dir: Path, |
| 66 | + *, |
| 67 | + run_turn: RunTurnFn, |
| 68 | + entry_agent_id: str, |
| 69 | +) -> None: |
| 70 | + """Set enriched manifest on the entry engine and bind ``LlmDelegator`` when peers exist. |
| 71 | +
|
| 72 | + When peers exist, ``use_tool_loop`` is enabled on the leaf engine so the LLM can |
| 73 | + emit ``delegate_to_*`` tool calls. A manifest or instantiation that set |
| 74 | + ``use_tool_loop=False`` is overridden with a warning. |
| 75 | + """ |
| 76 | + if engine is None: |
| 77 | + return |
| 78 | + leaf = _leaf_engine(engine) |
| 79 | + leaf.manifest = manifest |
| 80 | + if isinstance(leaf, LiveLlmEngine): |
| 81 | + leaf.manifest_dir = manifest_dir |
| 82 | + peers = delegation_targets(manifest, agent_id=entry_agent_id) |
| 83 | + if not peers: |
| 84 | + leaf.delegation = None |
| 85 | + return |
| 86 | + leaf.delegation = LlmDelegator(run_turn=run_turn) |
| 87 | + if hasattr(leaf, "use_tool_loop"): |
| 88 | + if not leaf.use_tool_loop: |
| 89 | + logger.warning( |
| 90 | + "entry agent %r: enabling use_tool_loop for dynamic delegation (%d peers)", |
| 91 | + entry_agent_id, |
| 92 | + len(peers), |
| 93 | + ) |
| 94 | + leaf.use_tool_loop = True |
| 95 | + |
| 96 | + |
| 97 | +def reset_engine_delegation(engine: Any) -> None: |
| 98 | + """Clear delegate caches at the start of each user turn.""" |
| 99 | + while engine is not None: |
| 100 | + delegation = getattr(engine, "delegation", None) |
| 101 | + reset_fn = getattr(delegation, "reset_session", None) |
| 102 | + if callable(reset_fn): |
| 103 | + reset_fn() |
| 104 | + engine = getattr(engine, "inner", None) |
0 commit comments