agent-works 0.1.6

Batteries-included Agent toolbox built on agent-base
Documentation
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
use std::collections::HashSet;
use std::sync::Arc;

use agent_base::{AgentResult, AgentRuntime, LlmClient, Tool};

use crate::multi_agent::{MultiAgentConfig, MultiAgentRuntime};

#[cfg(feature = "skill")]
use crate::skill::{LazySkillPrompter, Skill, SkillPrompter};

/// Factory type for creating multi-agent tools from a MultiAgentRuntime.
pub type MultiAgentToolFactory =
    Arc<dyn Fn(Arc<MultiAgentRuntime>) -> Vec<Arc<dyn Tool>> + Send + Sync>;

/// Factory type for creating a skill detail tool from skills and a tool name.
#[cfg(feature = "skill")]
pub type SkillDetailToolFactory =
    Arc<dyn Fn(Vec<Arc<dyn Skill>>, String) -> Arc<dyn Tool> + Send + Sync>;

/// Factory type for creating a list-skills tool from a SkillRegistry.
#[cfg(feature = "skill")]
pub type ListSkillsToolFactory =
    Arc<dyn Fn(Arc<crate::skill::SkillRegistry>) -> Arc<dyn Tool> + Send + Sync>;

pub struct AgentBuilder {
    inner: agent_base::AgentBuilder,
    system_prompt: Option<String>,
    tool_names: HashSet<String>,
    /// Business tools to pass to child agents (all registered tools).
    business_tools: Vec<Arc<dyn Tool>>,
    /// Multi-agent configuration (None = disabled).
    multi_agent_config: Option<MultiAgentConfig>,
    /// Factory to create multi-agent tools (injected by phi-kernel-tools).
    multi_agent_tool_factory: Option<MultiAgentToolFactory>,
    /// Error recovery (stored for multi-agent child inheritance).
    error_recovery: Option<Arc<dyn agent_base::ToolErrorRecovery>>,
    /// Language preference.
    language: Option<agent_base::Language>,
    #[cfg(feature = "skill")]
    skills: Vec<Arc<dyn Skill>>,
    #[cfg(feature = "skill")]
    skill_prompter: Option<Arc<dyn SkillPrompter>>,
    #[cfg(feature = "skill")]
    skill_detail_tool_name: String,
    /// Optional: inject a custom skill-detail tool (old tool-based mode).
    /// In default prompt-injection mode, the LLM reads `SKILL.md` via
    /// `read_file` — no dedicated detail tool is needed.
    #[cfg(feature = "skill")]
    skill_detail_tool_factory: Option<SkillDetailToolFactory>,
    #[cfg(feature = "skill")]
    list_skills_tool_factory: Option<ListSkillsToolFactory>,
    #[cfg(feature = "skill")]
    disable_skill_prompt_injection: bool,
}

impl AgentBuilder {
    pub fn new(client: Arc<dyn LlmClient>) -> Self {
        Self {
            inner: agent_base::AgentBuilder::new(client),
            system_prompt: None,
            tool_names: HashSet::new(),
            business_tools: Vec::new(),
            multi_agent_config: None,
            multi_agent_tool_factory: None,
            error_recovery: None,
            language: None,
            #[cfg(feature = "skill")]
            skills: Vec::new(),
            #[cfg(feature = "skill")]
            skill_prompter: None,
            #[cfg(feature = "skill")]
            skill_detail_tool_name: "get_skill_detail".to_string(),
            #[cfg(feature = "skill")]
            skill_detail_tool_factory: None,
            #[cfg(feature = "skill")]
            list_skills_tool_factory: None,
            #[cfg(feature = "skill")]
            disable_skill_prompt_injection: false,
        }
    }

    /// Enable multi-agent support with the given configuration.
    ///
    /// Also sets the tool factory to create the 6 multi-agent tools.
    /// Callers should use `phi_kernel_tools::multi_agent::create_all_tools` as the factory.
    pub fn with_multi_agent(mut self, config: MultiAgentConfig) -> Self {
        self.multi_agent_config = Some(config);
        self
    }

    /// Disable multi-agent support.
    ///
    /// Removes any previously set multi-agent configuration. No multi-agent tools
    /// will be registered and the system prompt will not mention multi-agent capabilities.
    pub fn without_multi_agent(mut self) -> Self {
        self.multi_agent_config = None;
        self.multi_agent_tool_factory = None;
        self
    }

    /// Set a custom factory for creating multi-agent tools.
    ///
    /// The factory receives the `MultiAgentRuntime` and returns the tools to register.
    /// If not set but multi-agent is enabled, no tools are registered (caller must
    /// set this for multi-agent to work).
    pub fn with_multi_agent_tool_factory(mut self, factory: MultiAgentToolFactory) -> Self {
        self.multi_agent_tool_factory = Some(factory);
        self
    }

    /// Set a custom factory for creating the skill detail tool.
    ///
    /// The factory receives the skill list and tool name, and returns the tool.
    /// If not set but skills are registered, no detail tool is added.
    #[cfg(feature = "skill")]
    pub fn with_skill_detail_tool_factory(mut self, factory: SkillDetailToolFactory) -> Self {
        self.skill_detail_tool_factory = Some(factory);
        self
    }

    /// Set a custom factory for creating the list-skills tool.
    ///
    /// The factory receives the SkillRegistry and returns the tool.
    #[cfg(feature = "skill")]
    pub fn with_list_skills_tool_factory(mut self, factory: ListSkillsToolFactory) -> Self {
        self.list_skills_tool_factory = Some(factory);
        self
    }

    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        let prompt = prompt.into();
        self.inner = self.inner.system_prompt(prompt.clone());
        self.system_prompt = Some(prompt);
        self
    }

    pub fn enable_thought(self, enable: bool) -> Self {
        Self {
            inner: self.inner.enable_thought(enable),
            ..self
        }
    }

    pub fn reasoning(self, config: agent_base::ReasoningConfig) -> Self {
        Self {
            inner: self.inner.reasoning(config),
            ..self
        }
    }

    pub fn enable_thinking(self, enable: bool) -> Self {
        Self {
            inner: self.inner.enable_thinking(enable),
            ..self
        }
    }

    pub fn thinking_budget(self, budget: u64) -> Self {
        Self {
            inner: self.inner.thinking_budget(budget),
            ..self
        }
    }

    pub fn tool_timeout(self, timeout_ms: u64) -> Self {
        Self {
            inner: self.inner.tool_timeout(timeout_ms),
            ..self
        }
    }

    pub fn max_tool_output_chars(self, max_chars: usize) -> Self {
        Self {
            inner: self.inner.max_tool_output_chars(max_chars),
            ..self
        }
    }

    pub fn max_sessions(self, max: usize) -> Self {
        Self {
            inner: self.inner.max_sessions(max),
            ..self
        }
    }

    pub fn max_turns_per_session(self, max: usize) -> Self {
        Self {
            inner: self.inner.max_turns_per_session(max),
            ..self
        }
    }

    pub fn execution_max_turns(self, max: u32) -> Self {
        Self {
            inner: self.inner.execution_max_turns(max),
            ..self
        }
    }

    pub fn max_message_tokens(self, max: usize) -> Self {
        Self {
            inner: self.inner.max_message_tokens(max),
            ..self
        }
    }

    pub fn register_tool(mut self, tool: impl Tool + 'static) -> Self {
        let tool_arc: Arc<dyn Tool> = Arc::new(tool);
        self.tool_names.insert(tool_arc.name().to_string());
        self.business_tools.push(tool_arc.clone());
        self.inner = self.inner.register_tool_arc(tool_arc);
        self
    }

    pub fn register_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
        self.tool_names.insert(tool.name().to_string());
        self.business_tools.push(tool.clone());
        self.inner = self.inner.register_tool_arc(tool);
        self
    }

    pub fn approval_handler(self, handler: Arc<dyn agent_base::ApprovalHandler>) -> Self {
        Self {
            inner: self.inner.approval_handler(handler),
            ..self
        }
    }

    pub fn tool_policy(self, policy: Arc<dyn agent_base::ToolPolicy>) -> Self {
        Self {
            inner: self.inner.tool_policy(policy),
            ..self
        }
    }

    pub fn middleware(self, mw: impl agent_base::Middleware + 'static) -> Self {
        Self {
            inner: self.inner.middleware(mw),
            ..self
        }
    }

    pub fn context_window(self, max_tokens: usize) -> Self {
        Self {
            inner: self.inner.context_window(max_tokens),
            ..self
        }
    }

    pub fn context_window_manager(self, manager: agent_base::ContextWindowManager) -> Self {
        Self {
            inner: self.inner.context_window_manager(manager),
            ..self
        }
    }

    pub fn response_format(self, format: agent_base::ResponseFormat) -> Self {
        Self {
            inner: self.inner.response_format(format),
            ..self
        }
    }

    pub fn llm_retry(self, retry: agent_base::RetryConfig) -> Self {
        Self {
            inner: self.inner.llm_retry(retry),
            ..self
        }
    }

    pub fn session_store(self, store: Arc<dyn agent_base::SessionStore>) -> Self {
        Self {
            inner: self.inner.session_store(store),
            ..self
        }
    }

    pub fn error_recovery(mut self, recovery: Arc<dyn agent_base::ToolErrorRecovery>) -> Self {
        self.error_recovery = Some(recovery.clone());
        self.inner = self.inner.error_recovery(recovery);
        self
    }

    pub fn tool_error_retry_prompt(self, prompt: impl Into<String>) -> Self {
        Self {
            inner: self.inner.tool_error_retry_prompt(prompt),
            ..self
        }
    }

    pub fn language(mut self, language: agent_base::Language) -> Self {
        self.language = Some(language.clone());
        self.inner = self.inner.language(language);
        self
    }

    pub fn event_bus_capacity(self, capacity: usize) -> Self {
        Self {
            inner: self.inner.event_bus_capacity(capacity),
            ..self
        }
    }

    pub fn session_id_generator(
        self,
        generator: Arc<dyn agent_base::types::SessionIdGenerator>,
    ) -> Self {
        Self {
            inner: self.inner.session_id_generator(generator),
            ..self
        }
    }

    /// Conditionally apply a transformation when `value` is `Some`.
    ///
    /// This is a convenience for option-chaining builder patterns:
    ///
    /// ```ignore
    /// builder.apply_if(args.thinking_budget, |b, budget| b.thinking_budget(budget))
    /// ```
    pub fn apply_if<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
        match value {
            Some(v) => f(self, v),
            None => self,
        }
    }

    #[cfg(feature = "skill")]
    pub fn register_skill(mut self, skill: impl Skill + 'static) -> Self {
        self.skills.push(Arc::new(skill));
        self
    }

    #[cfg(feature = "skill")]
    pub fn register_skills(mut self, skills: Vec<Arc<dyn Skill>>) -> Self {
        self.skills.extend(skills);
        self
    }

    #[cfg(feature = "skill")]
    pub fn skill_prompter(mut self, prompter: Arc<dyn SkillPrompter>) -> Self {
        self.skill_prompter = Some(prompter);
        self
    }

    #[cfg(feature = "skill")]
    pub fn disable_skill_prompt_injection(mut self) -> Self {
        self.disable_skill_prompt_injection = true;
        self
    }

    #[cfg(feature = "skill")]
    pub fn skill_detail_tool_name(mut self, name: impl Into<String>) -> Self {
        self.skill_detail_tool_name = name.into();
        self
    }

    // ── Build ──

    pub fn build(self) -> AgentResult<AgentRuntime> {
        #[cfg(feature = "skill")]
        {
            self.build_with_skills()
        }
        #[cfg(not(feature = "skill"))]
        {
            self.build_inner()
        }
    }

    #[allow(dead_code)]
    fn build_inner(mut self) -> AgentResult<AgentRuntime> {
        let lang = self.language.clone().unwrap_or_default();
        let ma_config = self.multi_agent_config.clone();
        let ma_tool_factory = self.multi_agent_tool_factory.take();
        let business_tools = std::mem::take(&mut self.business_tools);
        let error_recovery = self.error_recovery.clone();
        let tool_names = self.tool_names.clone();

        // Inject multi-agent prompt before build
        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
            let ma_prompt = build_multi_agent_system_prompt();
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
                None => ma_prompt,
            };
            self.inner = self.inner.system_prompt(new_prompt);
        }

        let runtime = self.inner.build()?;

        // Post-build: register multi-agent tools if enabled and factory is set
        if let Some(config) = ma_config
            && config.enabled
        {
            setup_multi_agent(
                &runtime,
                config,
                lang,
                business_tools,
                error_recovery,
                &tool_names,
                ma_tool_factory,
            )?;
        }

        Ok(runtime)
    }

    /// Build the runtime with skill support.
    ///
    /// # Runtime requirement
    ///
    /// This method uses [`tokio::task::block_in_place`] to populate the skill
    /// registry from a synchronous context. It **requires** a multi-threaded
    /// tokio runtime. Calling it on a `#[tokio::main]` single-threaded
    /// (`current_thread`) runtime will panic.
    ///
    /// The phi-agent CLI and all examples use the default multi-threaded runtime,
    /// so this is safe in practice.
    #[cfg(feature = "skill")]
    fn build_with_skills(mut self) -> AgentResult<AgentRuntime> {
        let mut ab = self.inner;
        let lang = self.language.clone().unwrap_or_default();
        let ma_config = self.multi_agent_config.clone();
        let ma_tool_factory = self.multi_agent_tool_factory.take();
        let business_tools = std::mem::take(&mut self.business_tools);
        let error_recovery = self.error_recovery.clone();
        let tool_names = self.tool_names.clone();

        // Process skills
        if !self.skills.is_empty() {
            let prompter: Arc<dyn SkillPrompter> = self
                .skill_prompter
                .take()
                .unwrap_or_else(|| Arc::new(LazySkillPrompter::new()));

            let mut skill_refs: Vec<Arc<dyn Skill>> = Vec::new();

            for skill in self.skills {
                for tool in skill.tools() {
                    let tool_name = tool.name().to_string();
                    if self.tool_names.contains(&tool_name) {
                        return Err(agent_base::AgentError::internal(format!(
                            "Tool name conflict: `{}` (Skill `{}`)",
                            tool_name,
                            skill.name()
                        )));
                    }
                    self.tool_names.insert(tool_name);
                    ab = ab.register_tool_arc(tool);
                }
                skill_refs.push(skill);
            }

            if !self.disable_skill_prompt_injection {
                let skill_prompt = prompter.build_prompt(&skill_refs, &self.skill_detail_tool_name);
                if !skill_prompt.is_empty() {
                    let new_prompt = match self.system_prompt.take() {
                        Some(existing) => format!("{}\n\n---\n\n{}", existing, skill_prompt),
                        None => skill_prompt,
                    };
                    self.system_prompt = Some(new_prompt.clone());
                    ab = ab.system_prompt(new_prompt);
                }
            }

            // Use injected factory if available, otherwise skip — prompt-injection
            // mode uses read_file instead of a dedicated detail tool.
            if let Some(factory) = self.skill_detail_tool_factory.take() {
                let detail_tool = factory(skill_refs.clone(), self.skill_detail_tool_name);
                ab = ab.register_tool_arc(detail_tool);
            }

            // Create SkillRegistry and populate it for the list-skills tool
            if let Some(factory) = self.list_skills_tool_factory.take() {
                let registry = Arc::new(crate::skill::SkillRegistry::new());
                for skill in &skill_refs {
                    tokio::task::block_in_place(|| {
                        tokio::runtime::Handle::current().block_on(async {
                            registry.register(skill.clone()).await;
                        })
                    });
                }
                let list_tool = factory(registry);
                ab = ab.register_tool_arc(list_tool);
            }
        }

        // Inject multi-agent prompt
        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
            let ma_prompt = build_multi_agent_system_prompt();
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
                None => ma_prompt,
            };
            ab = ab.system_prompt(new_prompt);
        }

        let runtime = ab.build()?;

        // Post-build: register multi-agent tools
        if let Some(config) = ma_config
            && config.enabled
        {
            setup_multi_agent(
                &runtime,
                config,
                lang,
                business_tools,
                error_recovery,
                &tool_names,
                ma_tool_factory,
            )?;
        }

        Ok(runtime)
    }
}

/// Set up the MultiAgentRuntime, event bridge, and register tools on an already-built runtime.
///
/// # Safety / Runtime Requirement
///
/// This function uses [`tokio::task::block_in_place`] to register tools synchronously.
/// It **requires** a multi-threaded tokio runtime. Calling it on a
/// `#[tokio::main]` single-threaded (`current_thread`) runtime will panic.
///
/// The phi-agent CLI and all examples use the default multi-threaded runtime,
/// so this is safe in practice.
pub fn setup_multi_agent(
    runtime: &AgentRuntime,
    config: MultiAgentConfig,
    lang: agent_base::Language,
    business_tools: Vec<Arc<dyn Tool>>,
    error_recovery: Option<Arc<dyn agent_base::ToolErrorRecovery>>,
    existing_tool_names: &HashSet<String>,
    tool_factory: Option<MultiAgentToolFactory>,
) -> AgentResult<Arc<MultiAgentRuntime>> {
    let client = runtime.client();
    let cancel_token = runtime.cancel_token();

    let ma_runtime = Arc::new(MultiAgentRuntime::new(
        config.clone(),
        client,
        business_tools,
        cancel_token,
        error_recovery,
        lang,
    ));

    // Set up event bridge: child events → parent event bus
    let (event_tx, mut event_rx) =
        tokio::sync::mpsc::unbounded_channel::<agent_base::RuntimeEvent>();
    ma_runtime.set_event_sender(event_tx);
    let parent_runtime = runtime.clone();
    tokio::spawn(async move {
        while let Some(event) = event_rx.recv().await {
            parent_runtime.emit_event(event);
        }
    });

    // Register multi-agent tools if a factory is provided
    if let Some(factory) = tool_factory {
        let tools = factory(ma_runtime.clone());
        let registry = runtime.tools_mut();
        let mut reg = tokio::task::block_in_place(|| registry.blocking_write());
        for tool in tools {
            let tool_name = tool.name().to_string();
            if !existing_tool_names.contains(&tool_name) {
                reg.register_arc(tool);
            }
        }
        drop(reg);
    }

    Ok(ma_runtime)
}

/// Build the multi-agent system prompt guidance for the main agent.
pub fn build_multi_agent_system_prompt() -> String {
    r#"## Multi-Agent Capabilities

You have the ability to spawn sub-agents to execute tasks concurrently. Use these tools to delegate work:

- `spawn_agent`: Create a new sub-agent with a specific role. The agent runs independently.
- `send_message`: Send a message to a sub-agent without triggering execution.
- `followup_task`: Assign a task to a sub-agent and trigger its execution. Returns immediately.
- `wait_agent`: Wait for a sub-agent's result. Blocks until the agent completes or timeout.
- `list_agents`: List all active sub-agents and their status.
- `close_agent`: Close a sub-agent and release its resources.

### When to Spawn

- Tasks that can run independently and in parallel (e.g., "research X and Y simultaneously")
- Long-running tasks where you want to check intermediate results
- Decomposing complex tasks into sub-tasks for focused execution

### When NOT to Spawn

- Simple lookups or single-tool calls (just use the tool directly)
- Sequential dependencies where the next step requires the previous result
- Tasks that need your full context or reasoning

### Communication Pattern

1. `spawn_agent` → create the sub-agent
2. `followup_task` → assign work (can call multiple times)
3. `wait_agent` → collect results
4. `close_agent` → clean up when done"#
        .to_string()
}

/// Build the memory system prompt guidance.
///
/// Tells the LLM how to use the file-based persistent memory system.
/// Memory is stored as markdown files — the LLM uses `read_file` / `write_file`
/// to manage them, following the same convention as Claude Code Memory.
///
/// This is prompt-injection only — no dedicated memory tools are registered.
/// The LLM uses the general-purpose file tools to read/write memory files.
pub fn build_memory_system_prompt() -> String {
    r#"## Memory

You have a persistent file-based memory at `.phi/memory/`. Use `read_file` and `write_file` to manage it — there are no dedicated memory tools.

### How Memory Works

- `MEMORY.md` is the index — it lists all memories with one-line descriptions. Read it first when you need to recall something.
- Each memory is a separate `.md` file with YAML frontmatter:
  ```yaml
  ---
  name: <short-kebab-case-slug>
  description: <one-line summary — used to decide relevance during recall>
  metadata:
    node_type: memory
    type: user | feedback | project | reference
  ---

  <the fact or instruction>
  ```
- The `description` field is the key for recall — write it so you can tell at a glance whether this memory is relevant to the current task.
- Link related memories with `[[memory-name]]` in the body.
- `user` type = who the user is (role, expertise, preferences).
- `feedback` type = guidance the user has given on how you should work.
- `project` type = ongoing work, goals, or constraints.
- `reference` type = pointers to external resources (URLs, dashboards, tickets).

### When to Use Memory

- The user explicitly asks you to remember something ("remember this", "save that")
- You learn something important about the user's preferences or workflow
- After completing a significant task, save context that would help in future sessions
- The user gives you feedback on how to work — save it as `feedback` type

### When NOT to Use Memory

- For transient information that won't be useful beyond this session
- For facts already recorded in the codebase (code structure, git history, config files)
- For items that only matter to the current conversation

### Pro Tips

- When creating your first memory of a new type, you can read template files for format reference (check `.phi/templates/memory/` if available).
- Keep the MEMORY.md index concise — it's loaded into context every session.
- Before writing a new memory, check if an existing file already covers it — update instead of duplicating.

### Workflow

**To recall:** read `MEMORY.md` → find relevant entries by description → read the specific `.md` files you need.
**To remember:** create a new `.md` file with proper frontmatter → update `MEMORY.md` with a new entry.
**To update:** edit the existing `.md` file (don't create a duplicate).
**To forget:** delete the `.md` file → remove its entry from `MEMORY.md`."#
        .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use agent_base::ToolControlFlow;
    use std::pin::Pin;

    // ── Stub LLM client ──

    struct StubClient;

    #[async_trait::async_trait]
    impl LlmClient for StubClient {
        async fn chat(
            &self,
            _messages: &[agent_base::ChatMessage],
            _tools: &[serde_json::Value],
            _reasoning: Option<&agent_base::ReasoningConfig>,
            _response_format: Option<&agent_base::ResponseFormat>,
        ) -> AgentResult<serde_json::Value> {
            Ok(serde_json::json!({"choices": [{"message": {"content": "ok"}}]}))
        }

        async fn chat_stream(
            &self,
            _messages: &[agent_base::ChatMessage],
            _tools: &[serde_json::Value],
            _reasoning: Option<&agent_base::ReasoningConfig>,
            _response_format: Option<&agent_base::ResponseFormat>,
        ) -> AgentResult<
            Pin<Box<dyn futures_core::Stream<Item = AgentResult<agent_base::StreamChunk>> + Send>>,
        > {
            let chunks: Vec<AgentResult<agent_base::StreamChunk>> = vec![
                Ok(agent_base::StreamChunk::Text("ok".to_string())),
                Ok(agent_base::StreamChunk::Stop),
            ];
            Ok(Box::pin(futures_util::stream::iter(chunks)))
        }

        fn capabilities(&self) -> agent_base::LlmCapabilities {
            agent_base::LlmCapabilities {
                supports_streaming: true,
                supports_tools: true,
                supports_vision: false,
                supports_thinking: false,
                max_context_tokens: None,
                max_output_tokens: None,
            }
        }
    }

    fn make_client() -> Arc<dyn LlmClient> {
        Arc::new(StubClient)
    }

    // ── setup_multi_agent tests ──

    #[tokio::test(flavor = "multi_thread")]
    async fn test_setup_multi_agent_without_factory_registers_no_tools() {
        let client = make_client();
        let runtime = agent_base::AgentBuilder::new(client.clone())
            .build()
            .unwrap();
        let config = MultiAgentConfig::enabled();

        let result = setup_multi_agent(
            &runtime,
            config,
            agent_base::Language::En,
            vec![],
            None,
            &HashSet::new(),
            None, // no factory
        );
        assert!(result.is_ok());
        let ma_runtime = result.unwrap();
        // Verify no tools were registered (the 6 multi-agent tools are absent)
        let agents = ma_runtime.list_agents();
        assert!(agents.is_empty());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_setup_multi_agent_with_factory_registers_tools() {
        let client = make_client();
        let runtime = agent_base::AgentBuilder::new(client.clone())
            .build()
            .unwrap();
        let config = MultiAgentConfig::enabled();

        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
            // Minimal factory returning a single fake tool
            struct FakeTool;
            #[async_trait::async_trait]
            impl Tool for FakeTool {
                fn name(&self) -> &'static str {
                    "fake_tool"
                }
                fn definition(&self) -> serde_json::Value {
                    serde_json::json!({"type": "function", "function": {"name": "fake_tool"}})
                }
                async fn call(
                    &self,
                    _args: &serde_json::Value,
                    _ctx: &agent_base::ToolContext,
                ) -> AgentResult<agent_base::ToolOutput> {
                    Ok(agent_base::ToolOutput {
                        summary: "ok".into(),
                        raw: None,
                        control_flow: ToolControlFlow::Continue,
                        truncation: None,
                    })
                }
            }
            vec![Arc::new(FakeTool)]
        });

        let result = setup_multi_agent(
            &runtime,
            config,
            agent_base::Language::En,
            vec![],
            None,
            &HashSet::new(),
            Some(factory),
        );
        assert!(result.is_ok());

        // Check the tool was registered on the runtime
        let tools: Vec<String> = tokio::task::block_in_place(|| {
            let tools = runtime.tools_mut();
            let guard = tools.blocking_read();
            guard.metadatas().into_iter().map(|m| m.name).collect()
        });
        assert!(tools.contains(&"fake_tool".to_string()));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_setup_multi_agent_skips_duplicate_tool_names() {
        let client = make_client();
        let runtime = agent_base::AgentBuilder::new(client.clone())
            .build()
            .unwrap();

        // Pre-register a tool with a conflicting name
        struct DupTool;
        #[async_trait::async_trait]
        impl Tool for DupTool {
            fn name(&self) -> &'static str {
                "dup_tool"
            }
            fn definition(&self) -> serde_json::Value {
                serde_json::json!({"type": "function", "function": {"name": "dup_tool"}})
            }
            async fn call(
                &self,
                _args: &serde_json::Value,
                _ctx: &agent_base::ToolContext,
            ) -> AgentResult<agent_base::ToolOutput> {
                Ok(agent_base::ToolOutput {
                    summary: "ok".into(),
                    raw: None,
                    control_flow: ToolControlFlow::Continue,
                    truncation: None,
                })
            }
        }
        {
            let tools = runtime.tools_mut();
            let mut reg = tokio::task::block_in_place(|| tools.blocking_write());
            reg.register(DupTool);
        }

        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
            struct FakeTool;
            #[async_trait::async_trait]
            impl Tool for FakeTool {
                fn name(&self) -> &'static str {
                    "dup_tool"
                }
                fn definition(&self) -> serde_json::Value {
                    serde_json::json!({"type": "function", "function": {"name": "dup_tool"}})
                }
                async fn call(
                    &self,
                    _args: &serde_json::Value,
                    _ctx: &agent_base::ToolContext,
                ) -> AgentResult<agent_base::ToolOutput> {
                    Ok(agent_base::ToolOutput {
                        summary: "ok".into(),
                        raw: None,
                        control_flow: ToolControlFlow::Continue,
                        truncation: None,
                    })
                }
            }
            vec![Arc::new(FakeTool)]
        });

        let mut existing = HashSet::new();
        existing.insert("dup_tool".to_string());

        let result = setup_multi_agent(
            &runtime,
            MultiAgentConfig::enabled(),
            agent_base::Language::En,
            vec![],
            None,
            &existing,
            Some(factory),
        );
        assert!(result.is_ok());
        // dup_tool should NOT have been registered twice
        let tools = tokio::task::block_in_place(|| {
            let tools = runtime.tools_mut();
            let guard = tools.blocking_read();
            guard
                .metadatas()
                .into_iter()
                .map(|m| m.name)
                .collect::<Vec<String>>()
        });
        let count = tools.iter().filter(|n| n.as_str() == "dup_tool").count();
        assert_eq!(count, 1);
    }

    // ── AgentBuilder factory methods ──

    #[tokio::test(flavor = "multi_thread")]
    async fn test_builder_with_multi_agent_without_factory_builds_ok() {
        let client = make_client();
        let runtime = AgentBuilder::new(client)
            .with_multi_agent(MultiAgentConfig::enabled())
            .build()
            .unwrap();
        // Should succeed even without a factory (no tools registered)
        let tools = tokio::task::block_in_place(|| {
            let tools = runtime.tools_mut();
            let guard = tools.blocking_read();
            guard
                .metadatas()
                .into_iter()
                .map(|m| m.name)
                .collect::<Vec<String>>()
        });
        // No multi-agent tools registered
        assert!(!tools.contains(&"spawn_agent".to_string()));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_builder_with_factory_registers_tools() {
        let client = make_client();
        // Create a simple factory that registers one recognizable tool
        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
            struct TestTool;
            #[async_trait::async_trait]
            impl Tool for TestTool {
                fn name(&self) -> &'static str {
                    "factory_test_tool"
                }
                fn definition(&self) -> serde_json::Value {
                    serde_json::json!({"type": "function", "function": {"name": "factory_test_tool"}})
                }
                async fn call(
                    &self,
                    _args: &serde_json::Value,
                    _ctx: &agent_base::ToolContext,
                ) -> AgentResult<agent_base::ToolOutput> {
                    Ok(agent_base::ToolOutput {
                        summary: "ok".into(),
                        raw: None,
                        control_flow: ToolControlFlow::Continue,
                        truncation: None,
                    })
                }
            }
            vec![Arc::new(TestTool)]
        });

        let runtime = AgentBuilder::new(client)
            .with_multi_agent(MultiAgentConfig::enabled())
            .with_multi_agent_tool_factory(factory)
            .build()
            .unwrap();

        let tools = tokio::task::block_in_place(|| {
            let tools = runtime.tools_mut();
            let guard = tools.blocking_read();
            guard
                .metadatas()
                .into_iter()
                .map(|m| m.name)
                .collect::<Vec<String>>()
        });
        assert!(tools.contains(&"factory_test_tool".to_string()));
    }

    #[test]
    fn test_builder_disabled_multi_agent_skips_factory() {
        let client = make_client();
        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
            panic!("factory should not be called when multi-agent is not configured");
        });

        let runtime = AgentBuilder::new(client)
            .with_multi_agent_tool_factory(factory)
            // Don't enable multi-agent — default (None) means disabled
            .build()
            .unwrap();

        let tools = tokio::task::block_in_place(|| {
            let tools = runtime.tools_mut();
            let guard = tools.blocking_read();
            guard
                .metadatas()
                .into_iter()
                .map(|m| m.name)
                .collect::<Vec<String>>()
        });
        assert!(!tools.contains(&"spawn_agent".to_string()));
    }

    // ── build_multi_agent_system_prompt ──

    #[test]
    fn test_system_prompt_contains_tool_names() {
        let prompt = build_multi_agent_system_prompt();
        assert!(prompt.contains("spawn_agent"));
        assert!(prompt.contains("send_message"));
        assert!(prompt.contains("followup_task"));
        assert!(prompt.contains("wait_agent"));
        assert!(prompt.contains("list_agents"));
        assert!(prompt.contains("close_agent"));
    }

    #[test]
    fn test_system_prompt_contains_guidance() {
        let prompt = build_multi_agent_system_prompt();
        assert!(prompt.contains("When to Spawn"));
        assert!(prompt.contains("When NOT to Spawn"));
        assert!(prompt.contains("Communication Pattern"));
    }

    // ── without_multi_agent ──

    #[tokio::test(flavor = "multi_thread")]
    async fn test_without_multi_agent_clears_config_and_factory() {
        let client = make_client();

        // Set up a factory that would panic if called — without_multi_agent should prevent it
        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
            panic!("factory should not be called when multi-agent is cleared");
        });

        let runtime = AgentBuilder::new(client)
            .with_multi_agent(MultiAgentConfig::enabled())
            .with_multi_agent_tool_factory(factory)
            .without_multi_agent() // clear both
            .build()
            .unwrap();

        let tools = tokio::task::block_in_place(|| {
            let tools = runtime.tools_mut();
            let guard = tools.blocking_read();
            guard
                .metadatas()
                .into_iter()
                .map(|m| m.name)
                .collect::<Vec<String>>()
        });
        assert!(!tools.contains(&"spawn_agent".to_string()));
    }

    // ── apply_if ──

    #[test]
    fn test_apply_if_some_applies_transformation() {
        let client = make_client();
        let builder = AgentBuilder::new(client)
            .apply_if(Some("custom prompt"), |b, prompt| b.system_prompt(prompt));
        // system_prompt is stored in self.system_prompt; verify it was set
        assert!(builder.system_prompt.unwrap().contains("custom prompt"));
    }

    #[test]
    fn test_apply_if_none_passes_through() {
        let client = make_client();
        let builder = AgentBuilder::new(client).apply_if(None as Option<&str>, |_b, _prompt| {
            panic!("should not be called when value is None");
        });
        assert!(builder.system_prompt.is_none());
    }

    // ── build_memory_system_prompt ──

    #[test]
    fn test_build_memory_system_prompt_non_empty() {
        let prompt = build_memory_system_prompt();
        assert!(!prompt.is_empty());
        assert!(prompt.contains("Memory"));
        assert!(prompt.contains("MEMORY.md"));
        assert!(prompt.contains("read_file"));
        assert!(prompt.contains("write_file"));
    }
}