
    i<                        d Z ddlZddlmZmZmZmZmZ ddlm	Z	m
Z
mZ ddlmZmZ ddlmZmZmZmZ ddlmZ ddlmZ dd	lmZm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$ ddl%m&Z& ddl'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z: ddl;m<Z<m=Z= ddl>m?Z@mAZB ddlCmDZD  G d deE      ZF G d d      ZGy)z>Graph orchestration adapted to ChatDev design_0.4.0 workflows.    N)AnyCallableDictListOptional)
MemoryBaseMemoryFactoryMemoryManager)ThinkingManagerBaseThinkingManagerFactory)NodeEdgeLinkAgentConfigConfigError)EdgeConditionConfig)SimpleMemoryConfig)MessageMessageRole)ExecutionContext)NodeExecutorFactory)WorkflowLogger)ValidationErrorWorkflowExecutionErrorWorkflowCancelledError)get_server_logger)CliPromptChannelHumanPromptServiceresolve_prompt_channel)CycleManager)GraphContext)GraphManager)ResourceManager)RuntimeBuilderResultArchiverDagExecutionStrategyCycleExecutionStrategyMajorityVoteStrategy)RuntimeContext)ConditionFactoryContextbuild_edge_condition_manager)ProcessorFactoryContextbuild_edge_processor)DynamicEdgeExecutorc                       e Zd ZdZy)ExecutionErrorz2Raised when the workflow graph cannot be executed.N)__name__
__module____qualname____doc__     ;/Users/bowang/.openclaw/workspace/ChatDev/workflow/graph.pyr/   r/   1   s    <r5   r/   c                      e Zd ZdZdddddedee   deeege	f      dee
j                     ddf
d	Zd=d
ee   ddfdZdefdZd>dZdefdZedddede	dee
j                     dd fd       Zde	fdZd>dZd>dZd>dZd>dZdefdZd>dZdefdZd>dZde	de ee	f   fdZ!d>dZ"de#de$de%ddfd Z&d!e%fd"Z'd!e%d#e(e$   de(e$   fd$Z)d!e%ddfd%Z*d!e%d&e(e$   de(e$   fd'Z+d>d(Z,defd)Z-de$dz  fd*Z.de(e$   fd+Z/de%fd,Z0d!e%d-e	defd.Z1d/e	defd0Z2d/e	de	fd1Z3d2e	de(e$   fd3Z4d4e$d5ede$fd6Z5d7e6d8ed9ede$fd:Z7d4e	d;ede$fd<Z8y)?GraphExecutorzTExecutes ChatDev_new graph workflows with integrated memory and thinking management.N)
session_idworkspace_hook_factorycancel_eventgraphr9   r:   r;   returnc                   d| _         || _        i | _        | j                         | _        |xs t        j                         | _        d| _        t        |      j                  | j                  |      }|r ||      |_        || _        |j                  | _        |j                  | _        |j                  | _        |j                   | _        t#        | j                         | _        i | _        i | _        i | _        |j,                  | _        |j.                  | _        |j0                  | _        d| _        d| _        i | _        d| _        g | _        y)z0Initialize executor with graph context instance.N)loggerr9   )majority_resultr<   outputs_create_loggerr?   	threadingEvent_cancel_event_cancel_reasonr#   buildworkspace_hookruntime_contexttool_managerfunction_manageredge_processor_function_managerlog_managerr"   resource_managerthinking_managersglobal_memoriesagent_memory_managerstoken_trackercode_workspaceattachment_storecycle_manager!_GraphExecutor__execution_contextnode_executors_human_prompt_serviceinitial_task_messages)selfr<   r9   r:   r;   runtimes         r6   __init__zGraphExecutor.__init__8   sA     $#(
))+)>Y__->-1 '--T[[Z-X!%;G%DG"&#00 ' 8 8/6/V/V,".. /0@0@ A BD68?A" %22 &44 ' 8 8 6: @D .0CG" 57"r5   reasonc                     |r|| _         n| j                   sd| _         | j                  j                          | j                  j	                  d| j
                  j                          y)z0Signal the executor to stop as soon as possible.Workflow execution cancelledz$Cancellation requested for workflow N)rF   rE   setr?   infor<   name)rZ   r]   s     r6   request_cancelzGraphExecutor.request_cancelh   sS    "(D$$"@D ?

?PQRr5   c                 6    | j                   j                         S N)rE   is_setrZ   s    r6   is_cancelledzGraphExecutor.is_cancelledq   s    !!((**r5   c                     | j                         r1| j                  xs d}t        || j                  j                        y )Nr_   )workflow_id)rh   rF   r   r<   rb   )rZ   messages     r6   _raise_if_cancelledz!GraphExecutor._raise_if_cancelledt   s9    ))K-KG(djjooNN r5   c                 j    t        | j                  j                  | j                  j                        S )z$Create and return a logger instance.)r   r<   rb   	log_levelrg   s    r6   rB   zGraphExecutor._create_loggery   s!    djjootzz/C/CDDr5   r;   task_promptc                <     | ||      }|j                  |       |S )z9Convenience method to execute a graph with a task prompt.ro   )_execute)clsr<   rp   r;   executors        r6   execute_graphzGraphExecutor.execute_graph}   s#     u<8+&r5   c                 |    | j                          | j                  |      }| j                  j                  |       y re   )rl   runr<   record)rZ   rp   resultss      r6   rr   zGraphExecutor._execute   s.      "((;'

'"r5   c                     | j                          | j                          | j                          | j                          y)z=Initialize all memory and thinking managers before execution.N)_build_global_memories_build_thinking_managers_build_agent_memories_build_node_executorsrg   s    r6   _build_memories_and_thinkingz*GraphExecutor._build_memories_and_thinking   s2    ##%%%'""$""$r5   c                    | j                   j                  j                         }|sy|D ]=  }|j                  | j                  v rCd|j                   }| j
                  j                  |       t        |d|j                  i      |j                  t              }|rR|j                  r|j                  dk(  r7| j                   j                  d|j                   dz  }t        |      |_
        	 t        j                  |      }|| j                  |j                  <   |j                          | j
                  j!                  d|j                   d	d|j                  i       @ y# t"        $ r}d
|j                   dt        |       }| j
                  j                  |d|j                  i       t%               }|j'                  |||j                         t)        |d|j                  i      d}~ww xY w)z"Build global memories from config.Nz!Duplicated memory name detected: memory_namedetailsautomemory_z.jsonzGlobal memory 'z' built successfullyzFailed to create memory '': )r   )r<   configget_memory_configrb   rP   rM   errorr   	as_configr   memory_path	directorystrr	   create_memoryloadra   	Exceptionr   log_exceptionr   )	rZ   memory_configstore	error_msg
simple_cfgpathmemory_instanceer?   s	            r6   r{   z$GraphExecutor._build_global_memories   s   

));;="EzzT111?

|L	  &&y1%i-9TUU);<J:#9#9Z=S=SW]=]zz++

|5.II),T
&]"/"="=e"D3B$$UZZ0$$&  %%%ejj\1EF*EJJ7 &  #&  ]7

|3s1vhO	  &&y=%**:U&V*,$$Q	uzz$J,YPUPZPZ@[\\]s   3A5E,,	G?5BG::G?c                     | j                   j                  j                         D ]V  \  }}|j                  t              }|s|j
                  s+t        j                  |j
                        | j                  |<   X y)z4Build thinking managers for nodes that require them.N)	r<   nodesitemsr   r   thinkingr   get_thinking_managerrO   )rZ   node_idnodeagent_configs       r6   r|   z&GraphExecutor._build_thinking_managers   s`    !ZZ--335MGT>>+6L 5 52H2]2] ))3&&w/ 6r5   c           
      h   | j                   j                  j                         D ]  \  }}|j                  t              }|r|j
                  s*	 t        |j
                  | j                        | j                  |<   | j                  j                  d| |d|j
                  D cg c]  }|j                   c}i        yc c}w # t        $ r^}d| dt        |       }| j                  j                  ||       t               }|j!                  |||       t#        ||      d}~ww xY w)z@Build memory managers for agent nodes referencing global stores.zMemory manager built for node memory_refs)r   r   z)Failed to create memory manager for node : )r   N)r<   r   r   r   r   memoriesr
   rP   rQ   rM   ra   rb   r   r   r   r   r   r   )rZ   r   r   r   memr   r   r?   s           r6   r}   z#GraphExecutor._build_agent_memories   s(   !ZZ--335MGT>>+6L \%:%:I6CLDYDY[_[o[o6p**73  %%4WI>#*AVAV,WAV#SXXAV,WX &  6 -X IGyPRSVWXSYRZ[	  &&y'&B*,$$Q	7$C,YHHIs,   AC
&C9	C
C

	D1AD,,D1c                    | j                   t        | j                  j                        }|j	                  d| j
                         | j                         }|j	                  d|       t        | j                  | j                  | j                  | j                  | j                  | j                  || j                  j                  || j                  
      | _         | j                   S )NrT   human_prompt)
rJ   rK   rM   memory_managersrO   rR   global_staterH   human_prompt_servicer;   )rV   dictrI   r   
setdefaultrT   _ensure_human_prompt_servicer   rJ   rK   rM   rQ   rO   rR   rH   rE   )rZ   r   prompt_services      r6   _get_execution_contextz$GraphExecutor._get_execution_context   s    ##+ 4 4 A ABL##$68M8MN!>>@N##NNC'7!..!%!6!6 ,, $ : :"&"8"8"00)#33BB%3!//(D$ '''r5   c                 ~    t        j                  | j                         | j                  j                        | _        y)z,Build node executors using strategy pattern.N)r   create_executorsr   r<   	subgraphsrW   rg   s    r6   r~   z#GraphExecutor._build_node_executors   s0     2BB'')JJ  
r5   c                    | j                   r| j                   S t        | j                  j                        }|
t	               }t        | j                  || j                  j                        | _         | j                   S )N)rM   channelr9   )rX   r   rI   rH   r   r   rM   r9   )rZ   r   s     r6   r   z*GraphExecutor._ensure_human_prompt_service   sp    %%---()=)=)L)LM?&(G%7((++66&
"
 )))r5   c                 b    | j                   j                         D ]  }|j                           y)z"Save all memories after execution.N)rP   valuessave)rZ   memorys     r6   _save_memorieszGraphExecutor._save_memories   s$    **113FKKM 4r5   c                    | j                          t        | j                        }	 |j                          | j                          | j                  j                  st        d      | j                  j                  | j                  j                         | j                          | j                  j                  r|j!                         | _        | j%                  |      D cg c]  }|j'                          c}| _        t+        | j                  j,                        }| j                  j.                  j1                         D ]q  \  }}| j                          |j3                          ||v s+d|_        |j7                          | j(                  D ]!  }	|j9                  |	j'                                # s | j                  j:                  rbt=        | j                  | j                  j.                  | j(                  | j>                  | j@                        }
|
jC                         | _"        n| j                  j                  rgtG        | j                  | j                  j.                  | j                  jH                  | j"                  | j>                        }
|
jC                          n[tK        | j                  | j                  j.                  | j                  j                  | j>                        }
|
jC                          | j                          | jM                          | jO                         }| jQ                          tS        | j                  | j                  | jT                        }|jW                  |       | jX                  S # t        $ r:}dt        |       }| j                  j                  j                  |       |d}~ww xY wc c}w )zQExecute the graph based on topological layers structure or cycle-aware execution.zGraph configuration error: Nz7Graph not built. Call GraphManager.build_graph() first.T)rM   r   initial_messagesexecute_node_funcpayload_to_text_func)rM   r   cycle_execution_orderrU   r   )rM   r   layersr   )-rl   r!   r<   build_graphr   r   rM   r?   r   _prepare_edge_conditionsr   r/   record_workflow_startmetadatar   
has_cyclesget_cycle_managerrU   _normalize_task_inputclonerY   r`   start_nodesr   r   reset_triggersstart_triggeredclear_inputappend_inputis_majority_votingr'   _execute_node_payload_to_textrw   r@   r&   r   r%   _collect_all_outputsget_final_outputr   r$   rR   exportrA   )rZ   rp   graph_managererrr   msgstart_node_idsr   r   rk   strategyfinal_resultarchivers                r6   rw   zGraphExecutor.run  s     "$TZZ0	%%' 	%%'zz   !Z[[ 	..tzz/B/BC 	))+ ::  !.!@!@!BD=A=W=WXc=d%e=dcciik=d%e"TZZ334 "ZZ--335MGT$$&!.('+$  "#99G%%gmmo6  : 6 ::((+ ,,jj&&!%!;!;"&"4"4%)%:%:H $,<<>D ZZ""- ,,jj&&&*jj&F&F"00"&"4"4H LLN+ ,,jj&&zz(("&"4"4	H LLN  " 	!!# ,,. "$**d.>.>@R@RS%||Y  	5c#hZ@I##)))4I	( &fs   N %O	O5OOc                    t        | j                  | j                        }t        | j                  | j                        }| j
                  j                  j                         D ]o  }|j                         D ]X  }|j                  }t        |t              sG|j                  j                  dd      }t        j                  ||j                   d      }||_	        	 t!        ||| j#                               }||_        t5        |d
d	      xs |j'                         }t5        |di       xs i }||_        ||_        |j.                  |_        |j<                  }|r]	 t?        ||      }||_         |j.                  |_!        t5        |di       xs i |_"        t5        |d
d	      }|s3||j                  d<   Dd	|_         i |_"        d	|_!        [ r y	# t$        $ rj}d|j'                          d| }	| j                  j)                  |	       t+               }
|
j-                  ||	|j.                         t1        |	      |d	}~ww xY w# t$        $ rj}d|j'                          d| }	| j                  j)                  |	       t+               }
|
j-                  ||	|j.                         t1        |	      |d	}~ww xY w)zACompile registered edge condition types into callable evaluators.rK   rM   	conditiontruez.edgesr   zFailed to prepare condition 'r   )condition_typeNlabelr   zFailed to prepare processor ')processor_typeprocess_label)#r)   rK   rM   PayloadProcessorFactoryContextrL   r<   r   r   iter_outgoing_edgescondition_config
isinstancer   r   get	from_dictr   r*   r   r   display_labelr   r   r   typer   condition_managergetattrr   condition_metadatar   process_configbuild_edge_payload_processorpayload_processorprocess_typeprocess_metadata)rZ   contextprocessor_contextr   	edge_linkr   	raw_valuemanagerexcr   r?   r   r   r   	processorprocessor_labels                   r6   r   z&GraphExecutor._prepare_edge_conditionsX  s   )4;P;P^b^n^no:!AA((
 JJ$$++-D!557	#,#=#= !"24GH ) 0 0 4 4[& II':'D'DYX\XaXaWbbhUi'j$1AI.E:;KWVZVqVqVstG /6	+$7[;K;Y;Y;["7J;Ar&+	#/7	,+;+@+@	(!*!9!9!	I$@Qb$c	 3<I/-;-@-@I*18JPR1S1YWYI.&-i$&GO&<K	((926I/13I.-1I*U 8 . ! E"?@P@^@^@`?aadehdi jI$$**95.0F((iHXH]H](^0;DE" % I;N<X<X<Z;[[^_b^cd " ((..y9!2!4,,S)NL_L_,`4Y?SHIs2   #G#I	I$A%I		I	KA%J??Kr   source_result	from_nodec                    |j                   }|0t        d|j                   d|j                  j                   d      	 |j	                  |||| j
                         y# t        $ r}d|j                   d|j                  j                   d| }| j
                  j                  ||j                  |j                  d	       t               }|j                  |||j                  |j                         t        |      |d}~ww xY w)
zPerform edge instantiation behavior.
        
        Edges with dynamic configuration still pass messages normally to the target
        node's input queue. Dynamic execution happens when the target node executes.
        NzEdge ->z is missing a condition managerzEdge manager failed for z -> r   )r   r   r   )r   r   idtargetprocessrM   r   r   r   r   r   r   )rZ   r   r   r   r   r   r   r?   s           r6   _process_edge_outputz"GraphExecutor._process_edge_output  s"    --?(	~R	(8(8(;(;'<<[\ 	=OO  	  	=*9<<.Y=M=M=P=P<QQSTWSXY  ""&/&>&>*3*F*F #  '(F  (77#,#?#?	 !  )3<%	=s    A 	D	(BDD	r   c                    ddl m} g }|j                  D ]Z  }|j                         D ]E  }|j                  |u s|j
                  |j                  |j                  |j
                  f       G \ |syt        |      dk(  r|d   d   S |d   \  }}|dd D ]  \  }}	|	j                  |j                  k7  r9t        d|j                   d| d|j                   d| d|	j                   d	      |	j                  j                  |j                  j                  k7  sZ|	j                  j                  |j                  j                  k7  s-|	j                  j                  |j                  j                  k7  rt        d|j                   d
| d| d      |	j                  |j                  k7  r9t        d|j                   d| d|j                   d| d|	j                   d      |	j                  dk(  sb|	j                  |j                  k7  s}t        d|j                   d| d|j                   d| d|	j                   d       |S )a   Get the dynamic configuration for a node from its incoming edges.
        
        If multiple incoming edges have dynamic config, they must be identical
        (same type and parameters). Otherwise raises an error.
        
        Returns the dynamic config if found, or None.
        r   )DynamicEdgeConfigN   zNode 'zH' has inconsistent dynamic configurations on incoming edges: edge from 'z' has type 'z', but edge from 'zF'. All dynamic edges to the same node must use the same configuration.zG' has inconsistent split configurations on incoming edges: edges from 'z' and 'zd' have different split settings. All dynamic edges to the same node must use the same configuration.z>' has inconsistent max_parallel on incoming edges: edge from 'z' has max_parallel=z, but edge from '.treez<' has inconsistent group_size on incoming edges: edge from 'z' has group_size=)'entity.configs.edge.dynamic_edge_configr  predecessorsr   r   dynamic_configappendr   lenr   r   splitpattern	json_pathmax_parallel
group_size)
rZ   r   r  found_configspredecessorr   first_sourcefirst_config	source_idr   s
             r6   _get_dynamic_config_for_nodez*GraphExecutor._get_dynamic_config_for_node  s    	N,,K(<<>	##t+	0H0H0T!((+..):R:R)ST ? -
 }" #A&& &31%5"l!.qr!2Iv{{l///,TWWI &"".|L<M<M;N O&&/[V[[M JZ[  !!\%7%7%<%<<$$(:(:(B(BB&&,*<*<*F*FF,TWWI &##/.	{ CZ[  ""l&?&??,TWWI &""./B<C\C\B] ^&&/[0CFDWDWCXXY[ 
 {{f$):):l>U>U)U,TWWI &""./@AXAX@Y Z&&/[0A&BSBSATTUW 5 "3@ r5   inputsc                     g }g }|D ]@  }|j                   j                  d      r|j                  |       0|j                  |       B  j                  j	                  d|j
                   d|j                   dt        |       dt        |       d	       dt        dt        t           d	t        t           f fd
}t         j                  |      }|j                  ||||      S )a`  Execute a node with dynamic configuration from incoming edges.
        
        Args:
            node: Target node to execute
            inputs: All input messages collected for this node
            dynamic_config: Dynamic configuration from the incoming edge
            
        Returns:
            Output messages from dynamic execution
        _from_dynamic_edgezExecuting node z with edge dynamic config (z mode): z dynamic inputs, z static inputsninpr=   c                 (    j                  | |      S re   )_process_result)r  r  rZ   s     r6   node_executor_funczFGraphExecutor._execute_with_dynamic_config.<locals>.node_executor_func  s    ''3//r5   )static_inputs)r   r   r  rM   ra   r   r   r  r   r   r   r-   execute_from_inputs)	rZ   r   r  r
  dynamic_inputsr   r   r  dynamic_executors	   `        r6   _execute_with_dynamic_configz*GraphExecutor._execute_with_dynamic_config  s    $ )+')C|| 45%%c*$$S)	  	dggY&A.BUBUAVV^>"##4S5G4HX	
	0$ 	0T'] 	0tG} 	0 /t/?/?AST  33.. 4 
 	
r5   c                 P
   | j                          | j                  j                  |      5  |j                  }|j	                          |D cg c]  }|j                  d       }}| j                  j                  |j                  ||j                  t        |      |j                  D cg c]  }|j                   c}|j                  D cg c]  }|j                   c}d       | j                  j                  dt        |       d|j                          | j                  |      }| j                  j                  |j                        5  || j!                  |||      }n| j#                  ||      }ddd       g }	D ]@  }
| j%                  |
|j                        }|j'                  |       |	j)                  |       B |	r|	d   nd}d}d}|5t+        |j,                  t.              r|j,                  j1                  d      }|j2                  dk7  r|r| j5                  ||      }|j2                  d	k7  ru|j7                  d
|j2                        }|r-| j                  j                  d|j                   d| d       n)| j                  j                  d|j                   d       |	rB| j                  j                  d|j                   dt        |       dt        |	       d       n)| j                  j                  d|j                   d       d}|	rt        |	      dk(  r|j9                         }n0t;        |	      D ]"  \  }}|d| d|j9                         z   dz   z  }$ |j<                  j>                  }|j,                  j1                  d      }nd}d}d}| j                  jA                  |j                  |jB                  r|ndt        |      t        |	      ||d       |	D ]*  }|jE                         D ]  }| jG                  |||        , |	r|j2                  dk7  r|stI        jJ                  d|jL                   d      }tO        |d      }||_(        tS        | jT                  | j                         }tW        ||| jY                               |_-        |j]                         |_/        |j`                  |_1        |	D ]  }| jG                  |||        ddd       yc c}w c c}w c c}w # 1 sw Y   xY w# 1 sw Y   yxY w)!zExecute a single node.Finclude_data)input_countr	  
successorszProcessing z inputs together for node Nr   context_traceT)preserve_keptcontext_windowNode z9 cleaned up its input context after execution (preserved z keep-marked inputs)z- cleaned up its input context after executionz processed z inputs into z
 output(s)z0 produced no output; downstream edges suppressed r  z===== OUTPUT z =====

z

sourcenone)output_sizeoutput_countoutput_roleoutput_sourcer   z.pseudo_edger   )r   triggerr   )2rl   rN   
guard_nodeinputr   to_dictrM   record_node_startr   	node_typer  r	  r)  debugr  
node_timerr$  r  _ensure_source_outputappend_outputr  r   r   r   r   r-  _restore_context_tracer   text_content	enumeraterolevaluerecord_node_end
log_outputr   r  r   r   r   r   r   r)   rK   r*   r   r   r   r   r   r   )rZ   r   input_resultsrk   serialized_inputspsr
  raw_outputsoutput_messages
raw_outputr   unified_outputcontext_trace_payloadcontext_restoredpreserved_inputsoutput_textidxr4  r5  
output_msgr   pseudo_conditionpseudo_linkpseudo_contexts                            r6   r   zGraphExecutor._execute_node#  s      """--d3 JJM !Ta bTae!DTa b ..tww8I4>>"=1/3/@/@ A/@!/@ A-1__=_qtt_=\  ""[]1C0DD^_c_f_f^g#hi ">>tDN !!,,TWW5!-"&"C"CD-Yg"hK"&"6"6t]"KK	 6 .0O)
00TWWE""3'&&s+ * 4C_Q/N$(!$)j9P9PRV.W(6(?(?(C(CO(T%""a',A#'#>#>tEZ#[ ""b(#'#3#3$W[WjWj#3#k #$$**y(abras  tH  I $$**y(UV   &&DGG9KM0B/C=QTUdQePffpq   &&DGG9$TU
 K'1,"0"="="?K$-o$>S#se:'FIYIYI['[^d'dd %?,1177 . 7 7 ; ;H E $ $,,TWWT__kZ\";/ #O 4*!.	_  .
!%!9!9!;I--iTJ "< . 4#6#6!#;DT#6#@#@QUQZQZP[[gNh#i &dEB/?,!8%)%:%: $ 0 0" 1MM]_mos  pK  pK  pM  1N-(8(F(F(H%-=-B-B*"1J--k:tL #2Q 43 !c
 !B= 65+ 43sP   !TT &AT,T?TT
"A3T)T>M9T TT	TT%input_payloadc                    | j                   st        d      |j                  | j                   vrt        d|j                         | j                   |j                     }| j                  j
                  }| j                  j                  }|r	 |j                  ||       d}	 |j                  ||      }d}||r	 |j                  |||       S S # t        $ r) | j                  j                  d|j                         Y bw xY w# t        $ r) | j                  j                  d|j                         Y S w xY w# |rK	 |j                  |||       w # t        $ r) | j                  j                  d|j                         Y w w xY ww xY w)zProcess a single input result using strategy pattern executors.

        This method delegates to specific node executors based on node type.
        Returns a list of messages (maybe empty if node suppresses output).
        zJNode executors not initialized. Call _build_memories_and_thinking() first.zUnsupported node type: z(workspace hook before_node failed for %sFT)successz'workspace hook after_node failed for %s)rW   RuntimeErrorr   
ValueErrorrI   rH   rS   before_noder   rM   warningr   execute
after_node)rZ   r   rX  rt   hook	workspacerZ  results           r6   r  zGraphExecutor._process_result  s    ""kll99D///6tyykBCC&&tyy1##22((77	^  y1 		a%%dM:FGaOOD)WOE   ^  (()SUYU\U\]^ ! a$$,,-VX\X_X_`a aOOD)WOE  a$$,,-VX\X_X_`a sT   C %D= =D/DD/D:9D:=FEF/FFFFc                    i }| j                   j                  r| j                   j                  j                         D ]y  \  }}|j                  s||j
                  t        |j                        t        |j                        |j                  D cg c]  }| j                  |       c}d}||d| <   { t        | d      r| j                  |d<   n| j                   j                  j                         D ]y  \  }}|j                  s||j
                  t        |j                        t        |j                        |j                  D cg c]  }| j                  |       c}d}||d| <   { t        | j                   j                        t        | j                   j                        t        | j                  j                         D cg c]	  }d|v s| c}      t        | j                   j                        d| j                   j                  d|d<   | j                  j!                  |       yc c}w c c}w c c}w )	z<Collect final outputs from all nodes, especially sink nodes.)r   r;  predecessors_numsuccessors_numry   node_r@   r   T)total_nodestotal_edgestotal_transmissionsr   execution_completedr   graph_summaryN)r<   r   r   r   outputr;  r  r	  r)  _serialize_output_payloadhasattrr@   edgesrA   keysr   update)rZ   all_outputsr   r   itemnode_outputks          r6   r   z"GraphExecutor._collect_all_outputs  s    ::((!%!1!1!7!7!9;;#*%)^^,/0A0A,B*-doo*>UYU`U`#aU`TD$B$B4$HU`#a#K 6AK%y 12 ": t./151E1E-. "&!1!1!7!7!9;;#*%)^^,/0A0A,B*-doo*>UYU`U`#aU`TD$B$B4$HU`#a#K 6AK%y 12 ": tzz//0tzz//0#&4<<3D3D3F'T3Fa$RS)3F'T#U$**++,#'"&**"?"?(
O$ 	K(= $b  $b (Us   H<I	IIc                 J    | j                         }|r|j                         S dS Nr/  )get_final_output_messagerA  )rZ   final_messages     r6   r   zGraphExecutor.get_final_output  s&    557/<}))+D"Dr5   c                    | j                   j                  ru| j                  y t        | j                  t              r| j                  j                         S | j                  t        j                  t        | j                        d      S | j                         }|sy |j                  rc|j                  d   }t        |t              r|j                         S | j                  t        j                  t        |      |j                        S y )NMAJORITY_VOTEr+  )r<   r   r@   r   r   r   _create_messager   	ASSISTANTr   _get_final_noderm  r   )rZ   
final_noderD  s      r6   ry  z&GraphExecutor.get_final_output_message  s    ::((##+$..8++1133''(=(=s4CWCW?XZijj))+
%%b)E%){{}$''(=(=s5z:==YYr5   c           	         | j                   j                  r| j                         }|r|gS g S | j                         }|sg S g }|j                  D ]u  }t        |t              r |j                  |j                                3|j                  | j                  t        j                  t        |      |j                               w |S )z(Return all messages from the final node.)r<   r   ry  r  rm  r   r   r  r   r}  r   r~  r   r   )rZ   r   r  ry   rD  s        r6   get_final_output_messagesz'GraphExecutor.get_final_output_messages  s    ::((//1CC5'R'))+
I&&E%)u{{}-t33K4I4I3u:WaWdWdef	 '
 r5   c                    | j                   j                  j                  j                  }|rI|D ]D  }|| j                   j                  v s| j                   j                  |   }|j
                  sB|c S  | j                   j                  j                         D cg c]  }|j                  r| }}|r|d   S dS c c}w )zDReturn the explicitly configured end node, or sink node as fallback.r   N)r<   r   
definition	end_nodesr   rm  r   r)  )rZ   end_node_idsend_node_idr   	sink_nodes        r6   r  zGraphExecutor._get_final_node  s    zz((33==+$**"2"22::++K8D{{#  , '+jj&6&6&=&=&?W&?dtT&?	W(y|2d2 Xs   B=.B=trace_payloadc                 (   t        |t              syd}|D ]  }t        |t              s	 t        j                  |      }|j
                  t        j                  t        j                  fvrW	 |j                  | j                  ||j                               |dz  } |r,| j                  j                  d|j                   d| d       |dkD  S # t        $ r5}| j                  j                  d|j                   d|        Y d }~d }~ww xY w)	NFr   z-Failed to deserialize context trace for node r   r  r.  z preserved z' messages from its tool execution trace)r   listr   r   r   rC  r   USERr~  r   rM   r^  r   r   _ensure_sourcer<  )rZ   r   r  restoredentryrk   r   s          r6   r@  z$GraphExecutor._restore_context_trace  s   -."EeT*!++E2<<(8(8+:O:O'PP Q d11'477CDMH # ""yH:5\] !|    ((CDGG9BseT 	s   AC	D+DDpayloadc                 ^    t        |t              r|j                         S |yt        |      S rx  )r   r   rA  r   rZ   r  s     r6   r   zGraphExecutor._payload_to_text2  s-    gw'''))?7|r5   c                 h    t        |t              rd|j                  d      dS dt        |      dS )Nrk   Fr&  )r   r  text)r   r   r9  r   r  s     r6   rn  z'GraphExecutor._serialize_output_payload9  s1    gw'%'//u/2UVV3w<88r5   	raw_inputc                    t        |t              rg }|D ]u  }t        |t              r"|j                  | j	                  |d             5t        |t
              sF|j                  | j                  t        j                  |d             w |xs" | j                  t        j                  dd      gS t        |t              r| j	                  |d      gS | j                  t        j                  t        |      d      gS )NTASKr/  )	r   r  r   r  r  r   r}  r   r  )rZ   r  messagesrt  s       r6   r   z#GraphExecutor._normalize_task_input>  s    i&&(H!dG,OOD$7$7f$EFc*OOD$8$89I9I4QW$XY	 "
 S 4 4[5E5Er6 RSSi)''	6:;;$$[%5%5s9~vNOOr5   rk   default_sourcec                     |j                         }t        |j                        }|j                  d|       ||_        |S Nr0  )r   r   r   r   )rZ   rk   r  clonedr   s        r6   r  zGraphExecutor._ensure_sourceK  s7    (Hn5"r5   rC  contentr0  c                 "    t        ||d|i      S )Nr0  )rC  r  r   )r   )rZ   rC  r  r0  s       r6   r}  zGraphExecutor._create_messageR  s    D'Xv<NOOr5   r   c                     t        |t              s*| j                  t        j                  t        |      |      S |j                         }t        |j                        }|j                  d|       ||_        |S r  )
r   r   r}  r   r~  r   r   r   r   r   )rZ   rk   r   r  r   s        r6   r>  z#GraphExecutor._ensure_source_outputU  sb    '7+''(=(=s7|WUU(()Hg."r5   re   )r=   N)9r0   r1   r2   r3   r    r   r   r   r(   r   rC   rD   r\   rc   boolrh   rl   r   rB   classmethodru   rr   r   r{   r|   r}   r   r   r~   r   r   r   r   rw   r   r   r   r   r  r  r   r$  r   r  r   r   ry  r  r  r@  r   rn  r   r  r   r}  r>  r4   r5   r6   r8   r8   5   s   ^ %)LP26.7.7 SM	.7
 !)>2BC2G)H I.7 y/.7 
.7`SXc] Sd S+d +O
E E  37

 

 y/
 

 
#C #
%]@I(((8 ((
*.@ *
Rs RtCH~ Rh22h-=-= #-= 	-=
 
-=`9 9v*
*
 W*

 
g*
XlM$ lM4 lM\aD ag a4PW= aB,)\E# E'D. $4= $3 3 4   4  9 9 9
Ps PtG} Pg s w PK P# Ps Pw PS 3 7 r5   r8   )Hr3   rC   typingr   r   r   r   r   runtime.node.agent.memoryr   r	   r
   runtime.node.agent.thinkingr   r   entity.configsr   r   r   r   entity.configs.edger   entity.configs.node.memoryr   entity.messagesr   r   runtime.node.executor.baser   runtime.node.executor.factoryr   utils.loggerr   utils.exceptionsr   r   r   utils.structured_loggerr   utils.human_promptr   r   r   workflow.cycle_managerr   workflow.graph_contextr    workflow.graph_managerr!   "workflow.executor.resource_managerr"   workflow.runtimer#   r$   r%   r&   r'    workflow.runtime.runtime_contextr(   runtime.edge.conditionsr)   r*   runtime.edge.processorsr+   r   r,   r   'workflow.executor.dynamic_edge_executorr-   r[  r/   r8   r4   r5   r6   <module>r     s    D  6 6 N N S C C 3 9 0 7 = ' \ \ 5 
 0 / / >  < H=\ =g gr5   