agent-works 0.17.0

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
// `Arc` is needed by every path that hands out a shared runtime, registry or
// prompter: the memory store, the skill registry/prompter, and the
// multi-agent runtime. Gate on all three, not on a subset — a feature set
// with `multi_agent` alone must still compile.
#[cfg(any(feature = "memory", feature = "skill", feature = "multi_agent"))]
use std::sync::Arc;

use agent_base::{AgentResult, AgentRuntime};

use super::AgentBuilder;
use super::build_agent_instructions_prompt;
#[cfg(feature = "memory")]
use super::build_memory_system_prompt_with_config;
#[cfg(feature = "multi_agent")]
use super::build_multi_agent_system_prompt;
#[cfg(feature = "multi_agent")]
use super::setup_multi_agent;

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

impl AgentBuilder {
    /// Register the four memory tools and append the memory prompt (index
    /// snapshot + tool guidance) to the system prompt. No-op when no memory
    /// configuration was set. Called from every `build_*` path right after
    /// the agent-instructions (CLAUDE.md) injection.
    #[cfg(feature = "memory")]
    fn apply_memory_config(mut self) -> Self {
        let Some(config) = self.memory_config.take() else {
            return self;
        };

        let store = Arc::new(MemoryStore::with_limits(
            config.memory_root.clone(),
            config.index_filename.clone(),
            config.limits.clone(),
        ));

        // Register the memory tools unless the consumer already took the name.
        for tool in crate::tools::create_memory_tools(Arc::clone(&store)) {
            let tool_name = tool.name().to_string();
            if self.tool_names.contains(&tool_name) {
                tracing::warn!(tool = %tool_name, "memory tool name conflict; skipping registration");
                continue;
            }
            self.tool_names.insert(tool_name);
            self.inner = self.inner.register_tool_arc(tool);
        }

        // Inject the index snapshot + tool guidance into the system prompt.
        // The snapshot is rebuilt from disk (the source of truth, design §4),
        // not read from a possibly-stale MEMORY.md; on a rebuild IO error fall
        // back to the raw snapshot rather than losing the index silently.
        let index = store.render_index().unwrap_or_else(|e| {
            tracing::warn!(error = %e, "memory index rebuild failed; using the raw MEMORY.md snapshot");
            store.read_index()
        });
        if index.len() > config.limits.index_max_bytes {
            tracing::warn!(
                index_bytes = index.len(),
                limit = config.limits.index_max_bytes,
                root = %config.memory_root.display(),
                "memory index is unusually large (over the configured max); consider cleaning up stale memories"
            );
        }
        let mem_prompt = build_memory_system_prompt_with_config(&config, &index);
        tracing::info!(
            memory_root = %config.memory_root.display(),
            index_bytes = index.len(),
            tools = 4,
            "injecting memory prompt + tools into system prompt"
        );
        let new_prompt = match self.system_prompt.take() {
            Some(existing) => format!("{existing}\n\n---\n\n{mem_prompt}"),
            None => mem_prompt,
        };
        tracing::info!(
            prompt_len = new_prompt.len(),
            "system prompt after memory injection (full text logged at DEBUG level)"
        );
        tracing::debug!(system_prompt = %new_prompt, "full system prompt after memory injection");
        self.system_prompt = Some(new_prompt.clone());
        self.inner = self.inner.system_prompt(new_prompt);
        self
    }

    // ── Build ──

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

    /// Build the runtime and return the multi-agent runtime (if enabled).
    ///
    /// Same as [`build`](Self::build) but also returns the `MultiAgentRuntime`
    /// created during setup. Callers that need to start the watcher task or
    /// access the mailbox should use this method.
    #[cfg(feature = "multi_agent")]
    pub fn build_with_ma(self) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
        #[cfg(feature = "skill")]
        {
            self.build_with_skills_ma()
        }
        #[cfg(not(feature = "skill"))]
        {
            self.build_inner_ma()
        }
    }

    #[allow(dead_code, unused_mut)]
    fn build_inner(mut self) -> AgentResult<AgentRuntime> {
        // Inject default guard if none was set by the consumer.
        // Uses the same LLM client for the judge (enabled by default).
        if self.inner.get_guard().is_none() {
            self.inner = self
                .inner
                .guard(crate::guard::DefaultGuard::with_llm_client(
                    crate::guard::DefaultGuardConfig::default(),
                    self.client.clone(),
                ));
        }

        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
        if !self.agent_instructions_paths.is_empty()
            && let Some(instructions) =
                build_agent_instructions_prompt(&self.agent_instructions_paths)
        {
            tracing::info!(
                paths = ?self.agent_instructions_paths,
                instructions_len = instructions.len(),
                "injecting agent instructions into system prompt"
            );
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
                None => instructions,
            };
            self.system_prompt = Some(new_prompt.clone());
            self.inner = self.inner.system_prompt(new_prompt);
        }

        // Register memory tools + inject memory prompt (Phase 9b)
        #[cfg(feature = "memory")]
        {
            self = self.apply_memory_config();
        }

        #[cfg(feature = "multi_agent")]
        let lang = self.language.clone().unwrap_or_default();
        #[cfg(feature = "multi_agent")]
        let business_tools = std::mem::take(&mut self.business_tools);
        #[cfg(feature = "multi_agent")]
        let error_recovery = self.error_recovery.clone();
        #[cfg(feature = "multi_agent")]
        let tool_names = self.tool_names.clone();

        #[cfg(feature = "multi_agent")]
        let ma_config = self.multi_agent_config.clone();
        #[cfg(feature = "multi_agent")]
        let ma_tool_factory = self.multi_agent_tool_factory.take();

        // Inject multi-agent prompt before build
        #[cfg(feature = "multi_agent")]
        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);
        }

        // Inject inline context compactor if set
        if let Some(compactor) = self.context_compactor.take() {
            self.inner = self.inner.context_compactor(compactor);
        }

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

        // Post-build: register multi-agent tools if enabled and factory is set
        #[cfg(feature = "multi_agent")]
        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)
    }

    /// Like `build_inner` but also returns the `MultiAgentRuntime`.
    #[cfg(feature = "multi_agent")]
    #[allow(dead_code, unused_mut)]
    fn build_inner_ma(mut self) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
        if self.inner.get_guard().is_none() {
            self.inner = self
                .inner
                .guard(crate::guard::DefaultGuard::with_llm_client(
                    crate::guard::DefaultGuardConfig::default(),
                    self.client.clone(),
                ));
        }

        // Register memory tools + inject memory prompt (Phase 9b)
        #[cfg(feature = "memory")]
        {
            self = self.apply_memory_config();
        }

        let lang = self.language.clone().unwrap_or_default();
        let business_tools = std::mem::take(&mut self.business_tools);
        let error_recovery = self.error_recovery.clone();
        let tool_names = self.tool_names.clone();
        let ma_config = self.multi_agent_config.clone();
        let ma_tool_factory = self.multi_agent_tool_factory.take();

        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);
        }

        if let Some(compactor) = self.context_compactor.take() {
            self.inner = self.inner.context_compactor(compactor);
        }

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

        let ma_runtime_out = if let Some(config) = ma_config
            && config.enabled
        {
            Some(setup_multi_agent(
                &runtime,
                config,
                lang,
                business_tools,
                error_recovery,
                &tool_names,
                ma_tool_factory,
            )?)
        } else {
            None
        };

        Ok((runtime, ma_runtime_out))
    }

    /// 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> {
        // Inject default guard if none was set by the consumer.
        // Uses the same LLM client for the judge (enabled by default).
        if self.inner.get_guard().is_none() {
            self.inner = self
                .inner
                .guard(crate::guard::DefaultGuard::with_llm_client(
                    crate::guard::DefaultGuardConfig::default(),
                    self.client.clone(),
                ));
        }

        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
        if !self.agent_instructions_paths.is_empty()
            && let Some(instructions) =
                build_agent_instructions_prompt(&self.agent_instructions_paths)
        {
            tracing::info!(
                paths = ?self.agent_instructions_paths,
                instructions_len = instructions.len(),
                "injecting agent instructions into system prompt"
            );
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
                None => instructions,
            };
            self.system_prompt = Some(new_prompt.clone());
            self.inner = self.inner.system_prompt(new_prompt);
        }

        // Register memory tools + inject memory prompt (Phase 9b)
        #[cfg(feature = "memory")]
        {
            self = self.apply_memory_config();
        }

        let mut ab = self.inner;
        #[cfg(feature = "multi_agent")]
        let lang = self.language.clone().unwrap_or_default();
        #[cfg(feature = "multi_agent")]
        let business_tools = std::mem::take(&mut self.business_tools);
        #[cfg(feature = "multi_agent")]
        let error_recovery = self.error_recovery.clone();
        #[cfg(feature = "multi_agent")]
        let tool_names = self.tool_names.clone();

        #[cfg(feature = "multi_agent")]
        let ma_config = self.multi_agent_config.clone();
        #[cfg(feature = "multi_agent")]
        let ma_tool_factory = self.multi_agent_tool_factory.take();

        // 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
        #[cfg(feature = "multi_agent")]
        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);
        }

        // Inject inline context compactor if set
        if let Some(compactor) = self.context_compactor.take() {
            ab = ab.context_compactor(compactor);
        }

        let runtime = ab.build()?;

        // Post-build: register multi-agent tools
        #[cfg(feature = "multi_agent")]
        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)
    }

    /// Like `build_with_skills` but also returns the `MultiAgentRuntime`.
    #[cfg(all(feature = "skill", feature = "multi_agent"))]
    fn build_with_skills_ma(
        mut self,
    ) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
        if self.inner.get_guard().is_none() {
            self.inner = self
                .inner
                .guard(crate::guard::DefaultGuard::with_llm_client(
                    crate::guard::DefaultGuardConfig::default(),
                    self.client.clone(),
                ));
        }

        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
        if !self.agent_instructions_paths.is_empty()
            && let Some(instructions) =
                build_agent_instructions_prompt(&self.agent_instructions_paths)
        {
            tracing::info!(
                paths = ?self.agent_instructions_paths,
                instructions_len = instructions.len(),
                "injecting agent instructions into system prompt"
            );
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
                None => instructions,
            };
            self.system_prompt = Some(new_prompt.clone());
            self.inner = self.inner.system_prompt(new_prompt);
        }

        // Register memory tools + inject memory prompt (Phase 9b)
        #[cfg(feature = "memory")]
        {
            self = self.apply_memory_config();
        }

        let mut ab = self.inner;
        let lang = self.language.clone().unwrap_or_default();
        let business_tools = std::mem::take(&mut self.business_tools);
        let error_recovery = self.error_recovery.clone();
        let tool_names = self.tool_names.clone();
        let ma_config = self.multi_agent_config.clone();
        let ma_tool_factory = self.multi_agent_tool_factory.take();

        // 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);
                }
            }

            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);
            }

            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);
        }

        if let Some(compactor) = self.context_compactor.take() {
            ab = ab.context_compactor(compactor);
        }

        let runtime = ab.build()?;

        let ma_runtime_out = if let Some(config) = ma_config
            && config.enabled
        {
            Some(setup_multi_agent(
                &runtime,
                config,
                lang,
                business_tools,
                error_recovery,
                &tool_names,
                ma_tool_factory,
            )?)
        } else {
            None
        };

        Ok((runtime, ma_runtime_out))
    }
}