
    ni                        d Z ddlmZ ddlZddlZddlmZ ddlmZ ddl	m
Z
 ddlmZmZmZ erddlmZ dd	lmZ d
ZddZ	 dddZdS )z?PM Agent router - routes discussion between participant Agents.    )annotationsN)TYPE_CHECKING)ValidationError)format_scratchpad_summary)AgentConfigMeetingState
PMDecision)ContextManager)	LLMClient   available_agentsdict[str, AgentConfig]returnstrc                p    d                     d |                                 D                       }d| dS )zBuild the PM Agent's system prompt with available agents listed.

    Args:
        available_agents: Mapping of agent name to AgentConfig.

    Returns:
        A fully-formed system prompt string for the PM LLM call.
    
c              3  6   K   | ]\  }}d | d|j          V  dS )z- z: N)role).0nameconfigs      -/root/projects/multi-agents-meeting/src/pm.py	<genexpr>z)build_pm_system_prompt.<locals>.<genexpr>   sJ        '3tV"T""V[""         zYou are a meeting facilitator (PM). Your job is to:
1. Analyze the current whiteboard state
2. Decide which Agent should speak next, or if the meeting should end
3. Output ONLY valid JSON matching the schema below

Available Agents:
a  

You MUST output ONLY a JSON object with these fields:
- "analysis": brief analysis of current whiteboard state
- "next_action": either "CALL_AGENT" or "FINISH"
- "target_agent": name of the agent to call (required if CALL_AGENT)
- "prompt_for_agent": specific question for that agent (required if CALL_AGENT)
- "final_report": complete Markdown meeting report (required if FINISH)

Rules:
- DO NOT wrap up prematurely. Explore the topic deeply before concluding.
- Ask follow-up questions when an agent gives a surface-level answer.
- Call the same agent multiple times if their area needs deeper exploration.
- Challenge assumptions: ask agents to justify their reasoning with specifics.
- Cross-pollinate: share one agent's perspective with another for counterpoints.
- Ensure at least 2-3 rounds of back-and-forth before considering FINISH.
- Call each agent at least once before finishing.
- When finishing, produce a comprehensive report that reflects the depth of discussion.
- The target_agent MUST be one of the available agents listed above.
- Output ONLY the JSON object, no other text.
- If you see entries from [HUMAN], treat them as high-priority stakeholder feedback.
  Address their concerns by calling relevant agents to respond.)joinitems)r   
agent_lists     r   build_pm_system_promptr      sb       7G7M7M7O7O    JC C C C Cr   stater   clientr   context_managerContextManager | Noner	   c                z   t          |          }||                    | |          }nDt          | j                  }d| j         d}| j        r|d| j         dz  }|d| j         d| z  }d|dg}d	}t          t                    D ]}	|r|	                    dd
| dd           |
                    ||          }
	 |
                                }|                    d          rUd|v r|                    dd          d         n|}|                    d          r
|dd         }|                                }|                    d          s6t          j        d|t          j                  }|r|                                }|                    d          rdd}d}d}t'          |          D ]N\  }}|rd}
|dk    r|rd}|dk    r| }|r"|dk    r|dz  }.|dk    r|dz  }|dk    r|d|dz            } nOt)          j        |          }t-          di |}|j        dk    r=|j        |vr4d|j         dd                    |                                           }|c S # t(          j        t8          f$ r}t;          |          }Y d}~d}~ww xY wt=          dt           d|           ) a  Run PM Agent to get the next routing decision.

    Calls the LLM with the current whiteboard state. Retries up to
    _MAX_RETRIES times when the response is invalid JSON, fails Pydantic
    validation, or references a non-existent agent. Each retry appends an
    error-feedback message so the LLM can self-correct.

    Args:
        state: Current MeetingState containing topic, scratchpad, and round.
        available_agents: Mapping of agent name to AgentConfig.
        client: Any object satisfying the LLMClient Protocol.
        context_manager: Optional ContextManager for whiteboard compression.

    Returns:
        A validated PMDecision instance.

    Raises:
        RuntimeError: When all retry attempts are exhausted without a valid decision.
    Nz## Meeting Topic

z

z## Background Context

z## Current Whiteboard (Round z)

user)r   content z$Your previous response was invalid: z . Please output ONLY valid JSON.)systemmessagesz```r      {z\{.*\}r   F\T"}
CALL_AGENTztarget_agent 'z!' is not available. Choose from: z, z&Failed to get valid PM decision after z attempts. Last error:  )r   build_pm_contextr   
scratchpadtopiccontextcurrent_roundrange_MAX_RETRIESappendchatstrip
startswithsplitendswithresearchDOTALLgroup	enumeratejsonloadsr	   next_actiontarget_agentr   keysJSONDecodeErrorr   r   RuntimeError)r   r   r    r!   system_promptuser_contentscratchpad_textr(   
last_errorattemptraw_responsecleanedmatchdepth	in_stringescape_nextichdatadecisionexcs                        r   run_pmrZ   @   s   2 ++;<<M"&77vFF3E4DEE?ek???= 	LKKKKKLc8KccRaccc/5,&O&O%PHJ&& C C 	OOn*nnn    
 {{-({KK:	"((**G!!%(( *7;w'--a0033G##E** +%crclG!--// %%c** ,	)Wbi@@ ,#kkmmG !!#&& "!	#&w// " "EAr" !&+ Tzziz&* Syy(1M	   ! Syy
s
 A::&-gAg&6G!E:g&&D!))D))H $44)1AAAIX%: I I$(II.>.C.C.E.E$F$FI I  OOO$o6 	 	 	SJHHHH	 	$ 	$ 	$!	$ 	$  s   F(I0,I00J JJ )r   r   r   r   )N)
r   r   r   r   r    r   r!   r"   r   r	   )__doc__
__future__r   rC   r>   typingr   pydanticr   	src.agentr   
src.modelsr   r   r	   src.context_managerr
   src.llm_clientr   r7   r   rZ   r0   r   r   <module>rc      s    E E " " " " " "  				             $ $ $ $ $ $ / / / / / / < < < < < < < < < < )222222(((((((C (C (C (C^ .2	o o o o o o or   