File size: 69,904 Bytes
8c6097b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
# Copyright (c) 2025 Huawei Technologies Co., Ltd. All rights reserved.
"""
Planner Agent for Multi-Agent Task Coordination

This agent serves as a coordinator for complex tasks that require multiple agents
working together. It implements the ReAct pattern for reasoning and action.
"""
import time
import json
import requests
import os
from typing import Dict, Any, List
from concurrent.futures import ThreadPoolExecutor

# Base imports
from .base_agent import BaseAgent, AgentConfig, AgentResponse, WriterAgentTaskInput
# Import agent creators for built-in task assignment
from .writer_agent import create_writer_agent


class PlannerAgent(BaseAgent):
    """
    PlannerAgent coordinates multiple agents to handle complex user queries.
    
    The agent uses the ReAct pattern (Reasoning + Acting) to analyze user requests,
    break them down into manageable tasks, and coordinate the appropriate agents
    to complete the work.
    """

    def __init__(self, config: AgentConfig = None, shared_mcp_client=None):
        # Set default agent name if not specified
        if config and not config.agent_name:
            config.agent_name = "PlannerAgent"
        elif not config:
            config = AgentConfig(agent_name="PlannerAgent")

        super().__init__(config, shared_mcp_client)

        # Planner-specific state
        self.execution_plan = []
        self.task_queue = []

        # Add built-in task assignment methods to available tools
        self._add_builtin_assignment_tools()

        # Regenerate tool schemas with built-in assignment tools
        self.tool_schemas = self._build_tool_schemas()

        self.sub_agent_configs = {}

    def _add_builtin_assignment_tools(self):
        """Add built-in task assignment methods as available tools"""
        # Add assignment methods that share the MCP client connection
        self.available_tools.update({
            "assign_subjective_task_to_writer": self.assign_subjective_task_to_writer, # assign_subjective_task_to_writer
            "assign_multi_objective_tasks_to_info_seeker": self.assign_multi_objective_tasks_to_info_seeker,
            "assign_multi_subjective_tasks_to_info_seeker": self.assign_multi_subjective_tasks_to_info_seeker
        })

    def assign_multi_objective_tasks_to_info_seeker(
            self,
            tasks: List[Dict[str, str]],
            max_workers: int = 5
        ) -> Dict[str, Any]:
        """
        Creates multiple TaskInput objects and routes them to info_seeker agents for concurrent execution.
        This tool enables the PlannerAgent to assign multiple research tasks through the MCP tool interface.
        
        Args:
            tasks: List of task dictionaries with the following keys:
                - task_content (required): The specific task content
                - task_steps_for_reference: Optional reference steps for execution
                - deliverable_contents: Format of expected deliverable
                - acceptance_checking_criteria: Criteria for task completion and quality
                - workspace_id: Workspace ID for stored files and memory
                - current_task_status: Description of current task status
                
            max_workers: Maximum concurrent threads (default=4)
            
        Returns:
            MCPToolResult with execution results for all tasks
        """
        try:
            # Validate task count (1-4 tasks)
            if not (1 <= len(tasks) <= 5):
                return {
                    "success": False,
                    "error": f"Invalid task count ({len(tasks)}). Must assign 1~5 tasks. Please re-plan the task execution schedule or re-decompose the task."
                }
            
            # Import here to avoid circular imports
            try:
                from agents import TaskInput, create_objective_information_seeker
            except ImportError:
                from ..agents import TaskInput, create_objective_information_seeker
            
            results = []
            import threading
            lock = threading.Lock()
            
            def process_task(task: Dict[str, str]):
                """Process a single task with thread-safe result collection"""
                try:
                    
                    
                    # Create TaskInput object
                    task_input = TaskInput(
                        task_content=task["task_content"],
                        task_steps_for_reference=task.get("task_steps_for_reference"),
                        deliverable_contents=task.get("deliverable_contents"),
                        current_task_status=task.get("current_task_status"),
                        workspace_id=None,  # Session/workspace is managed by the server; no need to set explicitly
                        acceptance_checking_criteria=task.get("acceptance_checking_criteria")
                    )
                    
                    # Create and execute with info seeker agent - use shared MCP client for session consistency
                    info_seeker_config = getattr(self, 'sub_agent_configs', {}).get('information_seeker', {})
                    info_seeker = create_objective_information_seeker(
                        model=info_seeker_config.get('model', self.config.model),
                        max_iterations=info_seeker_config.get('max_iterations', 30),
                        shared_mcp_client=self.mcp_tools.client if hasattr(self.mcp_tools, 'client') else self.mcp_tools
                    )

                    self.logger.info(f"Assigning task to InformationSeekerAgent: {task['task_content'][:8000]}...")

                    
                    # Execute the task
                    response = info_seeker.execute_task(task_input)

                    if response.success:
                        response_data = {
                            "task_content": task.get("task_content", "Unknown task"),
                            "success": True,
                            "data": response.result,
                            "agent_name": response.agent_name,
                            "iterations": response.iterations,
                            "execution_time": response.execution_time,
                            # "reasoning_trace": response.reasoning_trace
                        }
                    else:
                        response_data = {
                            "task_content": task.get("task_content", "Unknown task"),
                            "success": False,
                            "error": response.error,
                            "agent_name": response.agent_name
                        }                    
                    
                    # Thread-safe result collection
                    with lock:
                        results.append(response_data)
                    
                    return response_data
                    
                except Exception as e:
                    error_msg = f"Task processing failed: {str(e)}"
                    self.logger.error(error_msg)
                    with lock:
                        results.append({
                            "task_content": task.get("task_content", "Unknown task"),
                            "success": False,
                            "error": error_msg
                        })
                    return None
            
            # Execute tasks in parallel with thread pool
            with ThreadPoolExecutor(max_workers=max_workers) as executor:
                futures = [executor.submit(process_task, task) for task in tasks]
                # Wait for all tasks to complete
                for future in futures:
                    future.result()  # Raise exceptions if any
            
            # Check overall success
            all_success = all(task_result.get("success", False) for task_result in results)
            
            return {
                "success": all_success,
                "data": {"tasks": results},
                "error": None if all_success else "Some tasks failed",
                "metadata": {
                    "tool_name": "assign_multi_objective_tasks_to_info_seeker",
                    "task_count": len(tasks),
                    "success_count": sum(1 for r in results if r.get("success")),
                    "failure_count": sum(1 for r in results if not r.get("success"))
                }
            }
                
        except Exception as e:
            self.logger.error(f"Multi-task assignment failed: {e}")
            return {
                "success": False,
                "error": f"Multi-task assignment failed: {str(e)}"
            }
    

    def assign_multi_subjective_tasks_to_info_seeker(
            self,
            tasks: List[Dict[str, str]],
            max_workers: int = 5
    ) -> Dict[str, Any]:
        """
        Creates multiple TaskInput objects and routes them to info_seeker agents for concurrent execution.
        This tool enables the PlannerAgent to assign multiple research tasks through the MCP tool interface.
        
        Args:
            tasks: List of task dictionaries with the following keys:
                - task_content (required): The specific task content
                - task_steps_for_reference: Optional reference steps for execution
                - deliverable_contents: Format of expected deliverable
                - acceptance_checking_criteria: Criteria for task completion and quality
                - workspace_id: Workspace ID for stored files and memory
                - current_task_status: Description of current task status
                
            max_workers: Maximum concurrent threads (default=4)
            
        Returns:
            MCPToolResult with execution results for all tasks
        """
        try:
            # Validate task count (1-4 tasks)
            if not (1 <= len(tasks) <= 6):
                return {
                    "success": False,
                    "error": f"Invalid task count ({len(tasks)}). Must assign 1-6 tasks."
                }

            # Import here to avoid circular imports
            try:
                from agents import TaskInput, create_subjective_information_seeker
            except ImportError:
                from ..agents import TaskInput, create_subjective_information_seeker

            results = []
            import threading
            lock = threading.Lock()

            def process_task(task: Dict[str, str]):
                """Process a single task with thread-safe result collection"""
                try:
                    # Create TaskInput object
                    task_input = TaskInput(
                        task_content=task["task_content"],
                        task_steps_for_reference=task.get("task_steps_for_reference"),
                        deliverable_contents=task.get("deliverable_contents"),
                        current_task_status=task.get("current_task_status"),
                        workspace_id=self.get_session_info()["session_id"],  # Session/workspace is managed by the server; no need to set explicitly
                        acceptance_checking_criteria=task.get("acceptance_checking_criteria")
                    )

                    # Create and execute with info seeker agent - use shared MCP client for session consistency
                    info_seeker_config = getattr(self, 'sub_agent_configs', {}).get('information_seeker', {})
                    info_seeker = create_subjective_information_seeker(
                        model=info_seeker_config.get('model', self.config.model),
                        max_iterations=info_seeker_config.get('max_iterations', 30),
                        shared_mcp_client=self.mcp_tools.client if hasattr(self.mcp_tools, 'client') else self.mcp_tools
                    )

                    self.logger.info(f"Assigning task to InformationSeekerAgent: {task['task_content'][:8000]}...")

                    # Execute the task
                    response = info_seeker.execute_task(task_input)

                    if response.success:
                        response_data = {
                            "task_content": task.get("task_content", "Unknown task"),
                            "success": True,
                            "data": response.result,
                            "agent_name": response.agent_name,
                            "iterations": response.iterations,
                            "execution_time": response.execution_time,
                            # "reasoning_trace": response.reasoning_trace
                        }
                    else:
                        response_data = {
                            "task_content": task.get("task_content", "Unknown task"),
                            "success": False,
                            "error": response.error,
                            "agent_name": response.agent_name
                        }

                        # Thread-safe result collection
                    with lock:
                        results.append(response_data)

                    return response_data

                except Exception as e:
                    error_msg = f"Task processing failed: {str(e)}"
                    self.logger.error(error_msg)
                    with lock:
                        results.append({
                            "task_content": task.get("task_content", "Unknown task"),
                            "success": False,
                            "error": error_msg
                        })
                    return None

            # Execute tasks in parallel with thread pool
            with ThreadPoolExecutor(max_workers=max_workers) as executor:
                futures = [executor.submit(process_task, task) for task in tasks]
                # Wait for all tasks to complete
                for future in futures:
                    future.result()  # Raise exceptions if any

            # Check overall success
            all_success = all(task_result.get("success", False) for task_result in results)

            return {
                "success": all_success,
                "data": {"tasks": results},
                "error": None if all_success else "Some tasks failed",
                "metadata": {
                    "tool_name": "assign_multi_subjective_tasks_to_info_seeker",
                    "task_count": len(tasks),
                    "success_count": sum(1 for r in results if r.get("success")),
                    "failure_count": sum(1 for r in results if not r.get("success"))
                }
            }

        except Exception as e:
            self.logger.error(f"Multi-task assignment failed: {e}")
            return {
                "success": False,
                "error": f"Multi-task assignment failed: {str(e)}"
            }

    def assign_subjective_task_to_writer(
            self,
            task_content: str,
            user_query: str,
            key_files: List[Dict[str, str]]
    ) -> Dict[str, Any]:
        """
        Assign a writing or content creation task to the WriterAgent

        Args:
            task_content: Detailed description of the writing task to be performed
            user_query: List storing previous information seeker subtask summaries intact to preserve information from each completed research task
            key_files: Curated list of relevant files with file_path and desc for each file

        Returns:
            Dictionary with task assignment results
        """
        try:

            self.logger.info("Assigning task to WriterAgent")

            # Create task input
            task_input = WriterAgentTaskInput(
                task_content=task_content,
                user_query=user_query,
                key_files=key_files,
                workspace_id=self.get_session_info()["session_id"],
            )

            # Create writer agent with shared MCP client and sub-agent configuration
            writer_config = getattr(self, 'sub_agent_configs', {}).get('writer', {})
            writer = create_writer_agent(
                shared_mcp_client=self.mcp_tools.client,
                model=writer_config.get('model', self.config.model),
                max_iterations=writer_config.get('max_iterations', 20),
                temperature=writer_config.get('temperature', 0.3),
                max_tokens=writer_config.get('max_tokens', 16384)
            )

            self.logger.info(f"Assigning task to WriterAgent: {task_content[:800]}...")

            # Execute the task with shared connection
            response = writer.execute_task(task_input)

            if response.success:
                return {
                    "success": True,
                    "data": response.result,
                    "agent_name": response.agent_name,
                    "iterations": response.iterations,
                    "execution_time": response.execution_time,
                    # "reasoning_trace": response.reasoning_trace
                }
            else:
                return {
                    "success": False,
                    "error": response.error,
                    "agent_name": response.agent_name
                }

        except Exception as e:
            self.logger.error(f"Failed to assign task to WriterAgent: {e}")
            return {
                "success": False,
                "error": f"Task assignment failed: {str(e)}"
            }

    def _build_system_prompt(self) -> str:
        """Build the system prompt for the planner agent"""
        tool_schemas_str = json.dumps(self.tool_schemas, ensure_ascii=False)

        auto_system_prompt_template = """# PlannerAgent: Multi-Agent Task Coordinator
**Role:** Analyze complex queries, first distinguish query type (long-form writing type/objective question type), then create structured plans, and coordinate specialized agents to deliver comprehensive solutions—call corresponding tools based on query type, and only invoke writer for long-form writing type queries.

#### Available Sub-Agents:  
- **`information_seeker`**: Research, data gathering, web search (supports single/parallel multi-task; long-form writing type uses assign_multi_subjective_tasks_to_info_seeker, other types use assign_multi_objective_tasks_to_info_seeker)
- **`writer`**: Only invoke this sub-agent when long-form writing is required. 

---

## Optimized Workflow
### 1. Query Type Judgment & Analysis & Planning Phase
**Goal:** Use the `think` tool to analyze the problem and determine whether it is a simple task (refers to tasks that do not require calling the information search agent or tool) or a complex task (requires calling info seeker). If it is a complex task, it is necessary to further analyze whether it is a objective question(do not require calling the writer agent)or a long-form writing question (requires long-form expression and need to call the writer agent later).
- **Simple Tasks:** For simple tasks that do not require info seeker invocation, you can directly call the `planner_objective_task_done` tool and write the answer in `final_answer` field without creating a todo.md file.
- **Complex Tasks:**  
  - For objective tasks, must use `assign_multi_objective_tasks_to_info_seeker`
  - For long-form writing tasks, must use `assign_multi_subjective_tasks_to_info_seeker`, and call the writer agent to integrate the collected information to generate a very long text
  - **Task Decomposition Rules:** 
    - Construct a task tree with a tree-like structure, where the root node represents the user's input query. Each subtask is marked with its depth in the task tree, and the entire task tree is executed from shallow to deep. Tasks at the same depth in the task tree must be independent and can be executed in parallel (via `assign_multi_xxx_tasks_to_info_seeker`) without mutual dependencies.
    - At the first level of the task tree, it is essential to thoroughly design subtasks that can be executed in parallel to explore various potential background information, thereby providing more specific clues for the next step of planning.
    - Competitive Redundancy Mechanism:
      - For key subtasks that have a significant impact on subsequent reasoning and planning, a redundancy mechanism should be established. This involves duplicating the task at the same depth level in the task tree, enabling the parallel execution of nearly identical tasks to enhance the completion rate and robustness of the task execution.
  - **Task Parallel Sending Requirements:**
    - When using `assign_multi_xxx_tasks_to_info_seeker`, all parallel-sent subtasks must be independent of each other; the description of each subtask must not contain any mutual references or dependency requirements for other subtasks.
    - There is no sequential execution relationship among all parallel-sent subtasks.

  - **Mandatory Documentation:** Create and write `todo.md` (e.g., `todo_v1.md`) with fields:  
    ```markdown
    # Task Planning Document
    ## task_name: [Clear identifier]
    ## task_desc: [Detailed requirements - focus on WHAT not HOW]
    ## deliverable_contents: [Exact output format specs]
    ## success_criteria: [Measurable 100% completion metrics]
    ## context: [Background, constraints, prior results]
    ## task_steps_for_reference: [Tree-structured preliminary execution plan, tag tasks with the depth in task tree `[DEPTH:xx]`]
    ```  

### 2. Execution & Iteration Phase
#### A. Unified Iteration Triggers (Shared by Both Types)
- Based on upper-layer task results, refine the next layer of planning and document it in a new version of `todo.md` (e.g., `todo_v2.md`).  
- If upper-layer tasks fail/encounter challenges: Invoke the `reflect` tool for introspection (no new information acquired, only saves thoughts), adjust the plan, and re-invoke the corresponding `information_seeker` method (objective: `assign_multi_objective_tasks_to_info_seeker`; long-form writing: `assign_multi_subjective_tasks_to_info_seeker`).  
- If current tasks require prior round information: Clearly specify the context of each task and referenced files (e.g., `./data/agent_output_v1.json`) when calling `information_seeker`.  
- Decompose and refine clues from upper-layer results, then execute verification in parallel.  

#### B. Query-Type-Specific Operations
- **Objective tasks**: No additional operations (strictly no writer invocation). Continue iterating until information meets `success_criteria`.  
- **Long-form writing tasks**: Add **information sufficiency check before writer invocation**:  
  1. Evaluate collected information from two dimensions: quantity (e.g., "Enough case studies for 3 chapters") and comprehensiveness (e.g., "Covers both positive and negative impacts of AI on education").  
  2. If information is insufficient: Adjust subtask directions (e.g., "Supplement AI education failure cases") and re-invoke `assign_multi_subjective_tasks_to_info_seeker` for targeted collection.  
  3. If information is sufficient: Invoke the writer via `assign_subjective_task_to_writer` (provide all collected materials and `todo.md` as context).  
  4. If the writer returns an incomplete result: Do not assist in completing it; only feed back the current completion status to the user.  

### 3. Completion & Synthesis Phase
#### A. Unified Validation & Integration (Shared by Both Types)
- **Validation**: Cross-check multi-source `information_seeker` outputs for consistency (e.g., "NBS and World Bank GDP data differ by ≤1%").  
- **Integration**: Combine parallel outputs into a unified deliverable (e.g., "Merge two GDP data sources into a single table" or "Integrate writer’s report with supplementary case studies").  
- **Delivery**: Output language must match the user’s query language (e.g., Chinese query → Chinese deliverable).  

#### B. Query-Type-Specific Task Completion (Critical)
- **Objective tasks**: Call the `planner_objective_task_done` tool **only when** all planned tasks are completed and the final deliverable (e.g., verified data, clear answers) is ready for user delivery.  
- **Long-form writing tasks**: Call the `planner_subjective_task_done` tool **only when** the writer has finished executing and the final long-form content meets the `success_criteria` in `todo.md`.  

---

## Critical Protocols
1. **Dependency Management:**  
    - Prohibit parallel dispatch for sequential dependent tasks unless using competitive redundancy mechanism
    - Convert sequential chains to parallel where possible (e.g., Hypothesis_A vs Hypothesis_B testing)  
2. **File Traceability:**  
    - All output references use relative paths (`./data/agent_output_1.json`)  
    - Version `todo.md` after each iteration (e.g., `todo_v2.md`)
3. **Local File Reading Recommendations:**
    - For files crawled natively, it is not recommended to directly use the `file_read` tool to read the entire content (maybe too long). Instead, the `document_qa` tool should be used to extract and verify the required information.
    - For task deliverables and summary documents from sub-agents, the `file_read` tool can be used to read them.
4. The final deliverable presented to the user should be consistent with the language used in the user's question.
5. **Writer invocation**: Strictly prohibit calling the writer for objective tasks; for long-form writing tasks, **never directly answer based on collected information**—must invoke the writer to generate the final long-form content.

Below, within the <tools></tools> tags, are the descriptions of each tool and the required fields for invocation:
<tools>
$tool_schemas
</tools>
For each function call, return a JSON object placed within the [unused11][unused12] tags, which includes the function name and the corresponding function arguments:
[unused11][{\"name\": <function name>, \"arguments\": <args json object>}][unused12]"""

        writing_system_prompt_template = """### PlannerAgent: Multi-Agent Task Coordinator  
**Role:** Analyze complex queries, create structured plans, and coordinate specialized agents to deliver comprehensive solutions.  

#### Available Sub-Agents:  
- **`information_seeker`**: Research, data gathering, web search (supports single/parallel multi-task)  
- **`writer`**: Creates content (e.g., reports, analysis, etc.), and synthesizes from existing materials

---

### Optimized Workflow  
#### 1. Analysis & Planning Phase  
**Goal:** Analyze the problem and determine whether it is a simple task or a complex task. If it is a complex task, it is necessary to further analyze whether it is a subject-driven question or an objective-driven question, so as to decompose the problem into multiple clear and executable subtasks according to the specific problem type. The main characteristic of objective-driven questions is that their answers are clear and verifiable entities, otherwise they are subject-driven questions. 
- **Simple Tasks:** For simple tasks that do not require sub-agent invocation, you can directly answer without creating a todo.md file
- **Complex Tasks:**  
  - For Objective-driven tasks, Adopt *diverge-converge* strategy:  
    1. Use `assign_multi_subjective_tasks_to_info_seeker` call for divergent background research  
    2. Converge findings to define specific sub-problems  
  - For Subject-driven tasks, Adopt *multi-perspective* strategy:
    1. Use assign_multi_subjective_tasks_to_info_seeker call for divergent multi-source exploration (each task targets independent dimensions)
    2. Converge findings to define focused sub-problems addressing distinct knowledge gaps
    3. When the information seeker collects information, start to call the writer agent to integrate the collected information to generate a very long text
  - **Task Decomposition Rules:**  
    - Construct a task tree with a tree-like structure, where the root node represents the user's input query. Each subtask is marked with its depth in the task tree, and the entire task tree is executed from shallow to deep. Tasks at the same depth in the task tree must be independent and can be executed in parallel (via `assign_multi_subjective_tasks_to_info_seeker`) without mutual dependencies.
    - At the first level of the task tree, it is essential to thoroughly design subtasks that can be executed in parallel to explore various potential background information, thereby providing more specific clues for the next step of planning.
    - Competitive Redundancy Mechanism:
      - For key subtasks that have a significant impact on subsequent reasoning and planning, a redundancy mechanism should be established. This involves duplicating the task at the same depth level in the task tree, enabling the parallel execution of nearly identical tasks to enhance the completion rate and robustness of the task execution.
  - **Task Parallel Sending Requirements:**
    - When using `assign_multi_subjective_tasks_to_info_seeker`, all parallel-sent subtasks must be independent of each other; the description of each subtask must not contain any mutual references or dependency requirements for other subtasks.
    - There is no sequential execution relationship among all parallel-sent subtasks.

  - **Mandatory Documentation:** Create and write `todo.md` (e.g., `todo_v1.md`) with fields:  
    ```markdown
    # Task Planning Document
    ## task_name: [Clear identifier]
    ## task_desc: [Detailed requirements - focus on WHAT not HOW]
    ## deliverable_contents: [Exact output format specs]
    ## success_criteria: [Measurable 100% completion metrics]
    ## context: [Background, constraints, prior results]
    ## task_steps_for_reference: [Tree-structured preliminary execution plan, tag tasks with the depth in task tree `[DEPTH:xx]`]
    ```  

#### 2. Execution & Iteration Phase
- **Iteration Triggers:**
  - Based on the execution results of the upper layer of the task tree, specify and refine the next layer and subsequent task planning, and document them in a new `todo.md` file (e.g., `todo_v2.md`).
  - If there are tasks in the previous layer that have failed or encountered challenges, it is necessary to invoke `reflect` for introspection, consider more possibilities, and make new task planning and invoke `assign_multi_subjective_tasks_to_info_seeker` again. 
  - If the tasks sent in the current round require reference to task information from previous rounds, it is essential to clearly specify the context of each task and the files that may need to be used or referenced when calling `assign_multi_subjective_tasks_to_info_seeker`.
  - For the multiple clues of the execution results from the previous layer, they should be decomposed and refined, and executed in parallel for verification.
- **Information check required before calling writer:**  
  - Before invoking writer, analyze collected information for sufficiency: evaluate both quantity and comprehensiveness to ensure adequate material for long article generation
  - If information is insufficient, adjust subtask direction and initiate additional targeted information collection
- **When information is sufficient, invoke writer agent** via `assign_subjective_task_to_writer`

#### 3. Completion & Synthesis Phase  
- **Validation:** Cross-check multi-source outputs for consistency, and Check whether the information source is sufficient
- **Integration:** Combine parallel outputs into unified deliverable  
- **Delivery:** Output language must match user's query language  
- When the writer agent is finished executing, planner_subjective_task_done tool needs to be called to end the current task

---

### Critical Protocols  
1. **Dependency Management:**  
   - Prohibit parallel dispatch for sequential dependent tasks unless using competitive redundancy mechanism
   - Convert sequential chains to parallel where possible (e.g., Hypothesis_A vs Hypothesis_B testing)
2. **File Traceability:**  
   - All output references use relative paths (`./data/agent_output_1.json`)  
   - Version `todo.md` after each iteration (e.g., `todo_v2.md`)  
3. **Iteration Discipline:**  
   - Minimum 2 parallel agents for critical hypothesis-validation tasks  
   - Terminate only when ALL success criteria are met at 100%  
5. **Usage of Think Tool:**
   - `think` is a systematic tool. After receiving the response from the complex tool or before invoking any other tools, you must **first invoke the `think` tool**: to deeply reflect on the results of previous tool invocations (if any), and to thoroughly consider and plan the user's task. The `think` tool does not acquire new information; it only saves your thoughts into memory.
6. **Usage of Reflect Tool:**
    `reflect` is a systematic tool. When encountering a failure in tool execution, it is necessary to invoke the reflect tool to conduct a review and revise the task plan. It does not acquire new information; it only saves your thoughts into memory.
7. Always prioritize complete solutions over partial delivery. Use parallel redundancy for critical path tasks, and convert agent disagreements into new parallel investigation branches.
8. **CRITICAL:** When you determine that the information_seeker has gathered sufficient information, you must invoke the writer agent to draft the final article in response to the user's query. You are not allowed to reply directly based on the collected information!
9.Also note that when the writing agent returns a result that shows it is not completed, you do not need to help it complete it further. You only need to feedback the current completion status to the user.

Below, within the <tools></tools> tags, are the descriptions of each tool and the required fields for invocation:
<tools>
$tool_schemas
</tools>
For each function call, return a JSON object placed within the [unused11][unused12] tags, which includes the function name and the corresponding function arguments:
[unused11][{\"name\": <function name>, \"arguments\": <args json object>}][unused12]"""

        qa_system_prompt_template = """### PlannerAgent: Multi-Agent Task Coordinator  
**Role:** Analyze complex queries, create structured plans, and coordinate specialized agents to deliver comprehensive solutions.  

#### Available Sub-Agents:  
- **`information_seeker`**: Research, data gathering, web search (supports single/parallel multi-task)  

---

### Optimized Workflow  
#### 1. Analysis & Planning Phase  
**Goal:** Decompose problems into executable units with clear dependencies  
- **Simple Tasks:** For simple tasks that do not require sub-agent invocation, you can directly answer and call `planner_objective_task_done` without creating a todo.md file
- **Complex Tasks:**
  - **Task Decomposition Rules:**  
    - Construct a task tree with a tree-like structure, where the root node represents the user\'s input query. Each subtask is marked with its depth in the task tree, and the entire task tree is executed from shallow to deep. Tasks at the same depth in the task tree must be independent and can be executed in parallel (via `assign_multi_objective_tasks_to_info_seeker`) without mutual dependencies.
    - At the first level of the task tree, it is essential to thoroughly design subtasks that can be executed in parallel to explore various potential background information, thereby providing more specific clues for the next step of planning.
    - Competitive Redundancy Mechanism:
      - For key subtasks that have a significant impact on subsequent reasoning and planning, a redundancy mechanism should be established. This involves duplicating the task at the same depth level in the task tree, enabling the parallel execution of nearly identical tasks to enhance the completion rate and robustness of the task execution.
  - **Task Parallel Sending Requirements:**
    - When using `assign_multi_objective_tasks_to_info_seeker`, all parallel-sent subtasks must be independent of each other; the description of each subtask must not contain any mutual references or dependency requirements for other subtasks.
    - There is no sequential execution relationship among all parallel-sent subtasks.

  - **Mandatory Documentation:** Create and write `todo.md` (e.g., `todo_v1.md`) with fields:  
    ```markdown
    # Task Planning Document
    ## task_name: [Clear identifier]
    ## task_desc: [Detailed requirements - focus on WHAT not HOW]
    ## deliverable_contents: [Exact output format specs]
    ## success_criteria: [Measurable 100% completion metrics]
    ## context: [Background, constraints, prior results]
    ## task_steps_for_reference: [Tree-structured preliminary execution plan, tag tasks with the depth in task tree `[DEPTH:xx]`]
    ```  

#### 2. Execution & Iteration Phase
- **Iteration Triggers:**
  - Based on the execution results of the upper layer of the task tree, specify and refine the next layer and subsequent task planning, and document them in a new `todo.md` file (e.g., `todo_v2.md`).
  - If there are tasks in the previous layer that have failed or encountered challenges, it is necessary to invoke `reflect` for introspection, consider more possibilities, and make new task planning and invoke `assign_multi_objective_tasks_to_info_seeker` again. 
  - If the tasks sent in the current round require reference to task information from previous rounds, it is essential to clearly specify the context of each task and the files that may need to be used or referenced when calling `assign_multi_objective_tasks_to_info_seeker`.
  - For the multiple clues of the execution results from the previous layer, they should be decomposed and refined, and executed in parallel for verification.

#### 3. Completion & Synthesis Phase  
- **Validation:** Cross-check multi-source outputs for consistency
- **Integration:** Combine parallel outputs into unified deliverable  
- **Delivery:** Output language must match user\'s query language  
- **Task Completed:** The `planner_objective_task_done` can only be called when all planned tasks have been completed and the final results are ready to be delivered to the user.

---

### Critical Protocols  
1. **Dependency Management:**  
   - Prohibit parallel dispatch for sequential dependent tasks unless using competitive redundancy mechanism
   - Convert sequential chains to parallel where possible (e.g., Hypothesis_A vs Hypothesis_B testing)  
2. **File Traceability:**  
   - All output references use relative paths (`./data/agent_output_1.json`)  
   - Version `todo.md` after each iteration (e.g., `todo_v2.md`)
3. **Local File Reading Recommendations:**
    - For files crawled natively, it is not recommended to directly use the `file_read` tool to read the entire content (maybe too long). Instead, the `document_qa` tool should be used to extract and verify the required information.
    - For task deliverables and summary documents from sub-agents, the `file_read` tool can be used to read them.
4. The final deliverable presented to the user should be consistent with the language used in the user\'s question.

Below, within the <tools></tools> tags, are the descriptions of each tool and the required fields for invocation:
<tools>
$tool_schemas
</tools>
For each function call, return a JSON object placed within the [unused11][unused12] tags, which includes the function name and the corresponding function arguments:
[unused11][{\"name\": <function name>, \"arguments\": <args json object>}][unused12]"""

        planner_mode_system_prompt_map = {
            "auto": auto_system_prompt_template,
            "writing": writing_system_prompt_template,
            "qa": qa_system_prompt_template
        }

        system_prompt = planner_mode_system_prompt_map[self.config.planner_mode].replace("$tool_schemas", tool_schemas_str)

        return system_prompt

    def _build_agent_specific_tool_schemas(self) -> List[Dict[str, Any]]:
        """
        Build tool schemas for PlannerAgent using proper MCP architecture.
        Schemas come from MCP server via client, not direct imports.
        """

        # Get MCP tool schemas from server via client (proper MCP architecture)
        schemas = super()._build_agent_specific_tool_schemas()

        # Add schemas for built-in task assignment tools
        planner_mode_builtin_tools_map = {
            "auto": ["think", "reflect", "assign_multi_subjective_tasks_to_info_seeker", "assign_multi_objective_tasks_to_info_seeker", "assign_subjective_task_to_writer", "writer_subjective_task_done", "planner_subjective_task_done", "planner_objective_task_done"],
            "writing": ["think", "reflect", "assign_multi_subjective_tasks_to_info_seeker", "assign_subjective_task_to_writer", "writer_subjective_task_done", "planner_subjective_task_done"],
            "qa": ["think", "reflect", "assign_multi_objective_tasks_to_info_seeker", "planner_objective_task_done"],
        }
        builtin_assignment_schemas = [
            {
                "type": "function",
                "function": {
                    "name": "think",
                    "description": "Use the tool to think about something. It will not obtain new information or make any changes to the repository, but just log the thought. Use it when complex reasoning or brainstorming is needed.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "thought": {
                                "type": "string",
                                "description": "Your thoughts."
                            }
                        },
                        "required": ["thought"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "reflect",
                    "description": "When multiple attempts yield no progress, use this tool to reflect on previous reasoning and planning, considering possible overlooked clues and exploring more possibilities. It will not obtain new information or make any changes to the repository.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "reflect": {
                                "type": "string",
                                "description": "The specific content of your reflection"
                            }
                        },
                        "required": ["reflect"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "assign_multi_subjective_tasks_to_info_seeker",
                    "description": "Assign 1~6 research or information gathering tasks to different InformationSeekerAgents for parallel execution, each task descriptions must be semantically complete and clearly provide contextual information and potentially important reference documents.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "tasks": {
                                "type": "array",
                                "description": "List of tasks to be assigned to multiple InformationSeekerAgents",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "task_content": {
                                            "type": "string",
                                            "description": "Detailed description of the task to be performed"
                                        },
                                        "task_steps_for_reference": {
                                            "type": "string",
                                            "description": "Optional reference steps for task execution"
                                        },
                                        "deliverable_contents": {
                                            "type": "string",
                                            "description": "Expected format and content of deliverables"
                                        },
                                        "current_task_status": {
                                            "type": "string",
                                            "description": "Current status and context of the task, important documents that may be used and referenced"
                                        },
                                        "acceptance_checking_criteria": {
                                            "type": "string",
                                            "description": "Criteria for determining task completion and quality"
                                        },
                                    },
                                    "required": ["task_content"]
                                }
                            }
                        },
                        "required": ["tasks"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "assign_multi_objective_tasks_to_info_seeker",
                    "description": "Assign 1~5 research or information gathering tasks to different InformationSeekerAgents for parallel execution, each task descriptions must be semantically complete and clearly provide contextual information and potentially important reference documents.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "tasks": {
                                "type": "array",
                                "description": "List of tasks to be assigned to multiple InformationSeekerAgents",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "task_content": {
                                            "type": "string",
                                            "description": "Detailed description of the task to be performed, the task description must be semantically complete"
                                        },
                                        "task_steps_for_reference": {
                                            "type": "string",
                                            "description": "Optional reference steps for task execution"
                                        },
                                        "deliverable_contents": {
                                            "type": "string",
                                            "description": "Expected format and content of deliverables"
                                        },
                                        "current_task_status": {
                                            "type": "string",
                                            "description": "Current status and context of the task, important documents that may be used and referenced"
                                        },
                                        "acceptance_checking_criteria": {
                                            "type": "string",
                                            "description": "Criteria for determining task completion and quality, and the requirements in the event of task completion failure"
                                        },
                                    },
                                    "required": ["task_content"]
                                }
                            }
                        },
                        "required": ["tasks"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "assign_subjective_task_to_writer",
                    "description": "Assign a writing or content creation task to the WriterAgent",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "user_query": {
                                "type": "string",
                                "description": "Pass in the original user question."
                            },
                            "task_content": {
                                "type": "string",
                                "description": "Integrate and synthesize provided materials to generate comprehensive long-form content exceeding 10,000 words, especially careful not to give specific details, such as an outline plan, you are only providing the writer with a general description of the task."
                            },
                            "key_files": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "file_path": {
                                            "type": "string",
                                            "description": "Relative path to the file containing research content"
                                        }
                                    },
                                    "required": ["file_path"]
                                },
                                "description": "Collect all key_files returned by the information seeker for long-form content creation."
                            }
                        },
                        "required": ["user_query", "task_content", "key_files"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "writer_subjective_task_done",
                    "description": "Writer Agent task completion reporting for complete long-form content. Called after all chapters/sections are written to provide a summary of the complete long article, final completion status and analysis, and the storage path of the final consolidated article.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "final_article_path": {
                                "type": "string",
                                "description": "The file path where the final article is saved."
                            },
                            "article_summary": {
                                "type": "string",
                                "description": "Comprehensive summary of the complete long-form article, including main themes, key points covered, and overall narrative structure.",
                                "format": "markdown"
                            },
                            "completion_status": {
                                "type": "string",
                                "enum": ["completed", "partial", "failed"],
                                "description": "Final status of the complete long-form writing task"
                            },
                            "completion_analysis": {
                                "type": "string",
                                "description": "Analysis of the overall writing project completion including: assessment of article coherence and quality, evaluation of content organization and flow, identification of any challenges in the writing process, and overall evaluation of the long-form content creation success."
                            }
                        },
                        "required": ["final_article_path", "article_summary", "completion_status", "completion_analysis"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "planner_subjective_task_done",
                    "description": "When the writer agent is executed, the task done tool is called to end the planner's task.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "final_article_path": {
                                "type": "string",
                                "description": "The file path where the final article is saved."
                            },
                            "task_summary": {
                                "type": "string",
                                "description": "This field is mainly used to describe the main content of the article, briefly summarize it, and finally indicate the path where the final article is saved.",
                                "format": "markdown"
                            },
                            "task_name": {
                                "type": "string",
                                "description": "The name of the task currently assigned to the agent, usually with underscores (e.g., 'web_research_ai_trends')"
                            },
                            "completion_status": {
                                "type": "string",
                                "enum": ["completed", "partial", "failed"],
                                "description": "Final task status"
                            }
                        },
                        "required": ["final_article_path", "task_summary", "task_name", "completion_status"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "planner_objective_task_done",
                    "description": "Structured reporting of task completion details including summary, decisions, and final answer",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "task_summary": {
                                "type": "string",
                                "description": "Comprehensive markdown covering what the agent was asked to do, steps taken, tools used, key findings, files created, challenges",
                                "format": "markdown"
                            },
                            "task_name": {
                                "type": "string",
                                "description": "The name of the task currently assigned to the agent, usually with underscores (e.g., 'web_research_ai_trends')"
                            },
                            "key_files": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "file_path": {
                                            "type": "string",
                                            "description": "Relative path to created/modified file"
                                        },
                                        "desc": {
                                            "type": "string",
                                            "description": "File contents and creation purpose"
                                        },
                                        "is_final_output_file": {
                                            "type": "boolean",
                                            "description": "Whether file is primary deliverable"
                                        }
                                    },
                                    "required": ["file_path", "desc", "is_final_output_file"]
                                },
                                "description": "List of key files generated or modified during the task, with their details."
                            },
                            "completion_status": {
                                "type": "string",
                                "enum": ["completed", "partial", "failed"],
                                "description": "Final task status"
                            },
                            "final_answer": {
                                "type": "string",
                                "description": "The final response displayed to the user",
                            }
                        },
                        "required": ["task_summary", "task_name", "key_files", "completion_status", "final_answer"]
                    }
                }
            },
        ]

        used_builtin_schemas = [schema for schema in builtin_assignment_schemas if schema["function"]["name"] in planner_mode_builtin_tools_map[self.config.planner_mode]]
        schemas.extend(used_builtin_schemas)

        return schemas

    def _execute_react_loop(self, initial_message: str, max_iterations: int = 20) -> Dict[str, Any]:
        """
        Execute the ReAct loop for planning tasks

        Args:
            initial_message: Initial message to start the planning process
            max_iterations: Maximum number of iterations to perform

        Returns:
            Dictionary with execution results and trace
        """
        start_time = time.time()
        try:
            # Reset trace for new task
            self.reset_trace()
            # Initialize conversation history
            conversation_history = []

            # Build system prompt for planning
            system_prompt = self._build_system_prompt()
            # Add to conversation
            conversation_history.append({"role": "system", "content": system_prompt})
            conversation_history.append({"role": "user", "content": initial_message + " /no_think"})

            iteration = 0
            task_completed = False

            # Get model endpoint configuration from env-backed config
            from config.config import get_config
            config = get_config()
            model_config = config.get_custom_llm_config()
            
            pangu_url = model_config.get('url') or os.getenv('MODEL_REQUEST_URL', '')
            model_token = model_config.get('token') or os.getenv('MODEL_REQUEST_TOKEN', '')
            headers = {'Content-Type': 'application/json', 'csb-token': model_token}
            # ReAct Loop: Reasoning -> Acting -> Reasoning -> Acting...
            while iteration < self.config.max_iterations and not task_completed:
                iteration += 1
                self.logger.info(f"Planning iteration {iteration}")

                try:
                    # Get LLM response (reasoning + potential tool calls)
                    retry_num = 1
                    max_retry_num = 10
                    while retry_num < max_retry_num:
                        try:
                            response = requests.post(
                                url=pangu_url,
                                headers=headers,
                                json={
                                    "model": self.config.model,
                                    "chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<s>[unused9]系统:[unused10]' }}{% endif %}{% if message['role'] == 'system' %}{{'<s>[unused9]系统:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'assistant' %}{{'[unused9]助手:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'tool' %}{{'[unused9]工具:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'function' %}{{'[unused9]方法:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'user' %}{{'[unused9]用户:' + message['content'] + '[unused10]'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '[unused9]助手:' }}{% endif %}",
                                    "spaces_between_special_tokens": False,
                                    "messages": conversation_history,
                                    "temperature": self.config.temperature,
                                    "max_tokens": self.config.max_tokens,
                                },
                                timeout=model_config.get("timeout", 180)
                            )
                            response = response.json()
                            self.logger.debug(f"API response received")
                            break
                        except Exception as e:
                            time.sleep(3)
                            retry_num += 1
                            if retry_num == max_retry_num:
                                raise ValueError(str(e))
                            continue
                    assistant_message = response["choices"][0]["message"]

                    # Log the reasoning
                    try:
                        if assistant_message["content"]:
                            reasoning_content = assistant_message["content"].split("[unused16]")[-1].split("[unused17]")[0]
                            if len(reasoning_content) > 0:
                                self.log_reasoning(iteration, reasoning_content)
                    except Exception as e:
                        self.logger.warning(f"Tool call parsing error: {e}")
                        # Parse error, rerun
                        followup_prompt = f"There is a problem with the format of model generation: {e}. Please try again."
                        conversation_history.append({"role": "user", "content": followup_prompt + " /no_think"})
                        continue

                    def extract_tool_calls(content):
                        import re
                        if not content:
                            return []
                        tool_call_str = re.findall(r"\[unused11\]([\s\S]*?)\[unused12\]", content)
                        if len(tool_call_str) > 0:
                            try:
                                tool_calls = json.loads(tool_call_str[0].strip())
                            except:
                                return []
                        else:
                            return []
                        return tool_calls

                    # Add assistant message to conversation
                    conversation_history.append({
                        "role": "assistant",
                        "content": assistant_message["content"]
                    })

                    tool_calls = extract_tool_calls(assistant_message["content"])

                    # Execute tool calls if any (Acting phase)

                    for tool_call in tool_calls:
                        arguments = tool_call["arguments"]
                        self.logger.debug(f"Arguments is string: {isinstance(arguments, str)}")

                        # Check if planning is complete
                        if tool_call["name"] in ["planner_subjective_task_done", "planner_objective_task_done", "writer_subjective_task_done"]:
                            task_completed = True
                            self.log_action(iteration, tool_call["name"], arguments, arguments)
                            break
                        if tool_call["name"] in ["think", "reflect"]:
                            tool_result = {"tool_results": "You can proceed to invoke other tools if needed. "}
                        else:
                            tool_result = self.execute_tool_call(tool_call)

                        # Log the action using base class method
                        self.log_action(iteration, tool_call["name"], arguments, tool_result)

                        # Add tool result to conversation
                        conversation_history.append({
                            "role": "tool",
                            "content": json.dumps(tool_result, ensure_ascii=False, indent=2) + " /no_think"
                        })

                    # If no tool calls, encourage continued planning
                    if len(tool_calls) == 0:
                        # Add follow-up prompt to encourage action or completion
                        followup_prompt = (
                            "Continue your planning process. Use available tools to assign tasks to agents, "
                            "search for information, or coordinate work. When you have a complete answer, "
                            "call planner_subjective_task_done or planner_objective_task_done. /no_think"
                        )
                        conversation_history.append({"role": "user", "content": followup_prompt})

                except Exception as e:
                    error_msg = f"Error in planning iteration {iteration}: {e}"
                    self.log_error(iteration, error_msg)
                    break

            execution_time = time.time() - start_time

            # Extract final result
            if task_completed:
                # Find the completion result in the trace
                completion_result = None
                for step in reversed(self.reasoning_trace):
                    if step.get("type") == "action" and step.get("tool") in ["planner_subjective_task_done",
                                                                             "planner_objective_task_done"]:
                        completion_result = step.get("result")
                        break

                return {
                    "success": True,
                    "data": completion_result,
                    "reasoning_trace": self.reasoning_trace,
                    "iterations": iteration,
                    "execution_time": execution_time
                }
            else:
                return {
                    "success": False,
                    "error": f"Planning task not completed within {max_iterations} iterations",
                    "reasoning_trace": self.reasoning_trace,
                    "iterations": iteration,
                    "execution_time": execution_time
                }
        except Exception as e:
            execution_time = time.time() - start_time if 'start_time' in locals() else 0
            self.logger.error(f"Error in execute_react_loop: {e}")
            return {
                "success": False,
                "error": str(e),
                "reasoning_trace": self.reasoning_trace,
                "iterations": iteration if 'iteration' in locals() else 0,
                "execution_time": execution_time
            }


    def execute_task(self, user_query: str) -> AgentResponse:
        """
        Execute a planning task for the given user query

        Args:
            user_query: The user's query or request

        Returns:
            AgentResponse with planning results and process trace
        """
        start_time = time.time()

        try:
            self.logger.info(f"Starting planner task: {user_query}")

            # Execute the planning task using ReAct pattern
            result = self._execute_react_loop(
                initial_message=user_query,
                max_iterations=self.config.max_iterations  # Reasonable limit for planning tasks
            )

            execution_time = time.time() - start_time

            return AgentResponse(
                success=result.get("success", False),
                result=result.get("data"),
                error=result.get("error"),
                reasoning_trace=result.get("reasoning_trace", []),
                iterations=result.get("iterations", 0),
                execution_time=execution_time,
                agent_name=self.config.agent_name
            )

        except Exception as e:
            execution_time = time.time() - start_time
            self.logger.error(f"Planner execution failed: {e}")

            return AgentResponse(
                success=False,
                error=f"Planner execution failed: {str(e)}",
                reasoning_trace=[],
                iterations=0,
                execution_time=execution_time,
                agent_name=self.config.agent_name
            )


def create_planner_agent(
        model: Any = None,
        sub_agent_configs: Dict[str, Dict[str, Any]] = None,
        shared_mcp_client=None,
        **kwargs
) -> PlannerAgent:
    """
    Create a PlannerAgent instance with server-managed sessions.
    
    Args:
        model: The LLM model to use
        sub_agent_configs: Configuration for sub-agents (information_seeker, writer)
        shared_mcp_client: Optional shared MCP client to prevent duplicate connections
        **kwargs: Additional configuration options
        
    Returns:
        Configured PlannerAgent instance
    """
    # Import the enhanced config function
    from .base_agent import create_agent_config

    # Create agent configuration (session managed by MCP server)
    config = create_agent_config(
        agent_name="PlannerAgent",
        model=model,
        **kwargs
    )

    # Create planner agent with optional shared MCP client
    planner = PlannerAgent(config=config, shared_mcp_client=shared_mcp_client)

    # Store sub-agent configurations for use when creating sub-agents
    planner.sub_agent_configs = sub_agent_configs or {
        "information_seeker": {},
        "writer": {}
    }

    return planner