phi-core 0.7.0

Simple, effective agent loop with tool execution and event streaming
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
//! SystemPromptStrategy — structured system prompt composition.
//!
//! The system prompt is structured as **ordered blocks** with token budgets.
//! Three entities form a reference chain:
//!
//! 1. **SystemPromptStrategy** — defines the structure template (block names, order, max_length)
//! 2. **SystemPrompt** — fills content into a strategy's blocks (text or file paths)
//! 3. **AgentProfile.system_prompt** — references a SystemPrompt instance (or is raw text)
//!
//! # Example
//!
//! ```
//! use phi_core::agents::system_prompt::*;
//! use std::collections::HashMap;
//! use std::path::Path;
//!
//! // Define a strategy template
//! let strategy = CustomPromptStrategy {
//!     blocks: vec![
//!         PromptBlockDef { name: "identity".into(), order: 0, max_length: 500 },
//!         PromptBlockDef { name: "instructions".into(), order: 1, max_length: 2000 },
//!     ],
//! };
//!
//! // Fill content into the template
//! let mut blocks = HashMap::new();
//! blocks.insert("identity".into(), "You are Phi, an expert coder.".into());
//! blocks.insert("instructions".into(), "Write clean, well-tested code.".into());
//!
//! let prompt = SystemPrompt {
//!     id: "coder".into(),
//!     description: Some("Coding agent prompt".into()),
//!     strategy_ref: "agent_layout".into(),
//!     blocks,
//! };
//!
//! let result = prompt.compose(&strategy, Path::new(".")).unwrap();
//! assert!(result.contains("Phi"));
//! assert!(result.contains("well-tested"));
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

// ── Block definition ────────────────────────────────────────────────────────

/// A block definition within a SystemPromptStrategy (structure template).
///
/// Defines a named slot in the system prompt with an ordering and token budget.
/// The actual content is provided by a `SystemPrompt` instance.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PromptBlockDef {
    /// Block name (e.g., "identity", "instructions", "tools", "constraints").
    pub name: String,
    /// Assembly order — lower numbers appear first in the final prompt.
    pub order: u32,
    /// Maximum character budget for this block. Content exceeding this is truncated.
    pub max_length: usize,
}

// ── Strategy trait ──────────────────────────────────────────────────────────

/// Defines the structure template for a system prompt.
///
/// A strategy is reusable — multiple `SystemPrompt` instances can share one strategy,
/// each providing different content for the same block structure.
pub trait SystemPromptStrategy: Send + Sync {
    /// Return block definitions (structure only, no content).
    fn block_defs(&self) -> &[PromptBlockDef];
}

// ── Strategy implementations ────────────────────────────────────────────────

/// User-defined strategy with custom block definitions.
pub struct CustomPromptStrategy {
    pub blocks: Vec<PromptBlockDef>,
}

impl SystemPromptStrategy for CustomPromptStrategy {
    fn block_defs(&self) -> &[PromptBlockDef] {
        &self.blocks
    }
}

/// Predefined 4-block layout for general agents.
///
/// | Block | Order | Max Length |
/// |-------|-------|------------|
/// | identity | 0 | 500 |
/// | instructions | 1 | 2000 |
/// | tools | 2 | 1000 |
/// | constraints | 3 | 500 |
pub struct AgentPromptStrategy {
    blocks: Vec<PromptBlockDef>,
}

impl Default for AgentPromptStrategy {
    fn default() -> Self {
        Self {
            blocks: vec![
                PromptBlockDef {
                    name: "identity".into(),
                    order: 0,
                    max_length: 500,
                },
                PromptBlockDef {
                    name: "instructions".into(),
                    order: 1,
                    max_length: 2000,
                },
                PromptBlockDef {
                    name: "tools".into(),
                    order: 2,
                    max_length: 1000,
                },
                PromptBlockDef {
                    name: "constraints".into(),
                    order: 3,
                    max_length: 500,
                },
            ],
        }
    }
}

impl SystemPromptStrategy for AgentPromptStrategy {
    fn block_defs(&self) -> &[PromptBlockDef] {
        &self.blocks
    }
}

/// Predefined 2-block layout for simple agents.
///
/// | Block | Order | Max Length |
/// |-------|-------|------------|
/// | identity | 0 | 1000 |
/// | task | 1 | 3000 |
pub struct MinimalPromptStrategy {
    blocks: Vec<PromptBlockDef>,
}

impl Default for MinimalPromptStrategy {
    fn default() -> Self {
        Self {
            blocks: vec![
                PromptBlockDef {
                    name: "identity".into(),
                    order: 0,
                    max_length: 1000,
                },
                PromptBlockDef {
                    name: "task".into(),
                    order: 1,
                    max_length: 3000,
                },
            ],
        }
    }
}

impl SystemPromptStrategy for MinimalPromptStrategy {
    fn block_defs(&self) -> &[PromptBlockDef] {
        &self.blocks
    }
}

// ── SystemPrompt instance ───────────────────────────────────────────────────

/// A concrete system prompt instance: content mapped to a strategy's blocks.
///
/// Each block value is either:
/// - **Inline text**: `"You are an expert coder."`
/// - **Relative file path**: `"file:prompts/identity.md"` — resolves from agent workspace
/// - **Absolute file path**: `"file:/etc/phi/identity.md"` — resolves as-is
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemPrompt {
    /// Unique id (uses `{{...}}` reference protocol in config).
    pub id: String,
    /// Description for existence check queries (with `%` references).
    pub description: Option<String>,
    /// Reference to the strategy that defines this prompt's structure.
    pub strategy_ref: String,
    /// Block name → content mapping.
    pub blocks: HashMap<String, String>,
}

impl SystemPrompt {
    /// Compose the final system prompt text by resolving blocks against the strategy.
    ///
    /// - Sorts blocks by strategy order
    /// - Resolves `"file:path"` references (relative paths use `working_dir`)
    /// - Truncates each block to its `max_length`
    /// - Concatenates with double newlines
    pub fn compose(
        &self,
        strategy: &dyn SystemPromptStrategy,
        working_dir: &Path,
    ) -> Result<String, std::io::Error> {
        let mut defs: Vec<&PromptBlockDef> = strategy.block_defs().iter().collect();
        defs.sort_by_key(|d| d.order);

        let mut parts = Vec::new();
        for def in &defs {
            if let Some(raw) = self.blocks.get(&def.name) {
                let content = resolve_content(raw, working_dir)?;
                parts.push(truncate_to_chars(&content, def.max_length));
            }
        }
        Ok(parts.join("\n\n"))
    }
}

// ── Helpers ─────────────────────────────────────────────────────────────────

/// Resolve block content: if prefixed with "file:", read from disk.
/// Relative paths resolve from `working_dir`.
fn resolve_content(raw: &str, working_dir: &Path) -> Result<String, std::io::Error> {
    if let Some(path_str) = raw.strip_prefix("file:") {
        let path = Path::new(path_str);
        let full_path = if path.is_absolute() {
            path.to_path_buf()
        } else {
            working_dir.join(path)
        };
        std::fs::read_to_string(full_path)
    } else {
        Ok(raw.to_string())
    }
}

/// Truncate a string to at most `max_chars` characters.
fn truncate_to_chars(s: &str, max_chars: usize) -> String {
    if s.len() <= max_chars {
        s.to_string()
    } else {
        s.chars().take(max_chars).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_custom_strategy_block_defs() {
        let strategy = CustomPromptStrategy {
            blocks: vec![
                PromptBlockDef {
                    name: "a".into(),
                    order: 1,
                    max_length: 100,
                },
                PromptBlockDef {
                    name: "b".into(),
                    order: 0,
                    max_length: 200,
                },
            ],
        };
        assert_eq!(strategy.block_defs().len(), 2);
    }

    #[test]
    fn test_agent_prompt_strategy_has_4_blocks() {
        let s = AgentPromptStrategy::default();
        assert_eq!(s.block_defs().len(), 4);
        assert_eq!(s.block_defs()[0].name, "identity");
        assert_eq!(s.block_defs()[3].name, "constraints");
    }

    #[test]
    fn test_minimal_prompt_strategy_has_2_blocks() {
        let s = MinimalPromptStrategy::default();
        assert_eq!(s.block_defs().len(), 2);
        assert_eq!(s.block_defs()[0].name, "identity");
        assert_eq!(s.block_defs()[1].name, "task");
    }

    #[test]
    fn test_compose_orders_by_block_order() {
        let strategy = CustomPromptStrategy {
            blocks: vec![
                PromptBlockDef {
                    name: "second".into(),
                    order: 2,
                    max_length: 1000,
                },
                PromptBlockDef {
                    name: "first".into(),
                    order: 0,
                    max_length: 1000,
                },
                PromptBlockDef {
                    name: "middle".into(),
                    order: 1,
                    max_length: 1000,
                },
            ],
        };
        let mut blocks = HashMap::new();
        blocks.insert("first".into(), "AAA".into());
        blocks.insert("middle".into(), "BBB".into());
        blocks.insert("second".into(), "CCC".into());
        let prompt = SystemPrompt {
            id: "test".into(),
            description: None,
            strategy_ref: "test".into(),
            blocks,
        };
        let result = prompt.compose(&strategy, Path::new(".")).unwrap();
        assert_eq!(result, "AAA\n\nBBB\n\nCCC");
    }

    #[test]
    fn test_compose_truncates() {
        let strategy = CustomPromptStrategy {
            blocks: vec![PromptBlockDef {
                name: "a".into(),
                order: 0,
                max_length: 5,
            }],
        };
        let mut blocks = HashMap::new();
        blocks.insert("a".into(), "hello world".into());
        let prompt = SystemPrompt {
            id: "test".into(),
            description: None,
            strategy_ref: "test".into(),
            blocks,
        };
        let result = prompt.compose(&strategy, Path::new(".")).unwrap();
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_compose_skips_missing_blocks() {
        let strategy = CustomPromptStrategy {
            blocks: vec![
                PromptBlockDef {
                    name: "a".into(),
                    order: 0,
                    max_length: 1000,
                },
                PromptBlockDef {
                    name: "b".into(),
                    order: 1,
                    max_length: 1000,
                },
                PromptBlockDef {
                    name: "c".into(),
                    order: 2,
                    max_length: 1000,
                },
            ],
        };
        let mut blocks = HashMap::new();
        blocks.insert("a".into(), "first".into());
        blocks.insert("c".into(), "third".into());
        // b is missing
        let prompt = SystemPrompt {
            id: "test".into(),
            description: None,
            strategy_ref: "test".into(),
            blocks,
        };
        let result = prompt.compose(&strategy, Path::new(".")).unwrap();
        assert_eq!(result, "first\n\nthird");
    }

    #[test]
    fn test_compose_reads_file() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("identity.txt");
        std::fs::write(&file_path, "I am a test agent").unwrap();

        let strategy = CustomPromptStrategy {
            blocks: vec![PromptBlockDef {
                name: "identity".into(),
                order: 0,
                max_length: 1000,
            }],
        };
        let mut blocks = HashMap::new();
        blocks.insert("identity".into(), "file:identity.txt".into());
        let prompt = SystemPrompt {
            id: "test".into(),
            description: None,
            strategy_ref: "test".into(),
            blocks,
        };
        let result = prompt.compose(&strategy, dir.path()).unwrap();
        assert_eq!(result, "I am a test agent");
    }

    #[test]
    fn test_compose_file_not_found() {
        let strategy = CustomPromptStrategy {
            blocks: vec![PromptBlockDef {
                name: "a".into(),
                order: 0,
                max_length: 1000,
            }],
        };
        let mut blocks = HashMap::new();
        blocks.insert("a".into(), "file:nonexistent.txt".into());
        let prompt = SystemPrompt {
            id: "test".into(),
            description: None,
            strategy_ref: "test".into(),
            blocks,
        };
        let result = prompt.compose(&strategy, Path::new("."));
        assert!(result.is_err());
    }
}