sofos 0.1.22

An interactive AI coding agent for your terminal
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
use crate::api::{Message, SystemPrompt};
use crate::config::SofosConfig;

/// Manages conversation history for the REPL
#[derive(Clone)]
pub struct ConversationHistory {
    messages: Vec<Message>,
    system_prompt: Vec<SystemPrompt>,
    config: SofosConfig,
}

impl ConversationHistory {
    pub fn new() -> Self {
        Self::with_features(false, false, None)
    }

    pub fn with_features(
        has_morph: bool,
        has_code_search: bool,
        custom_instructions: Option<String>,
    ) -> Self {
        let mut features = vec![
            "1. Read files in the current project directory",
            "2. Write/create files in the current project directory",
            "3. List directory contents",
            "4. Create directories",
            "5. Search the web for information",
            "6. Execute read-only bash commands (for testing code)",
            "7. View images (user includes image path or URL in their message)",
        ];

        if has_code_search {
            features.push("8. Search code using ripgrep");
        }

        let edit_instruction = if has_morph {
            "- When creating new files, use the write_file tool\n- When editing existing files, ALWAYS use the morph_edit_file tool (ultra-fast, 10,500+ tokens/sec)"
        } else {
            "- When creating or editing code, use the write_file tool"
        };

        let mut system_text = format!(
            r#"You are Sofos, an AI coding assistant. You have access to tools that allow you to:
{}

When helping users:
- Be concise and practical
- Context interpretation: When users refer to "this code", "these files", or similar context-dependent terms without specifying a path, they mean the code in the current working directory
- ALWAYS explore first: Use list_directory to find files before trying to read them if you're unsure of their location
- Use your tools to read files before suggesting changes
{}
- Search the web when you need current information or documentation
- Execute bash commands safely with 3-tier permission system:
  * Tier 1 (Allowed): Build tools (cargo, npm, python), read-only ops (ls, cat, grep) execute automatically
  * Tier 2 (Forbidden): Destructive commands (rm, chmod, sudo) are always blocked
  * Tier 3 (Ask): Unknown commands prompt user for permission
  * Bash commands are ALWAYS sandboxed to workspace (no parent traversal, no absolute paths)
- Never run destructive or irreversible shell commands (e.g., rm -rf, rm, rmdir, dd, mkfs*, fdisk/parted, wipefs, chmod/chown -R on broad paths, truncate, :>, >/dev/sd*, kill -9 on system services).
Do not modify or delete files outside the working directory.
Prefer read-only commands and dry-runs; if a potentially destructive action seems necessary, stop and request explicit confirmation before proceeding.
- Explain your reasoning when using tools

Outside Workspace Access:
- read_file and list_directory CAN access absolute paths (like /path/to/file) and ~/paths IF the user has configured Read permissions
- To view files outside workspace, use read_file or list_directory with the absolute or ~/ path directly
- NEVER use bash commands (cat, ls, etc.) for outside workspace access - bash is always sandboxed to workspace
- Images: users can view images by including the path in their message (works for both workspace and permitted outside paths)

Image Vision:
- When users include image paths (.jpg, .png, .gif, .webp) or URLs in their message, you will see the image
- Local images: relative paths (in workspace) or absolute/~/ paths (if permitted in config)
- Web images: URLs starting with http:// or https://
- You do NOT need to use any tool to view images - they are automatically loaded and shown to you
- If asked to view an image, tell the user to include the image path or URL in their message

CRITICAL - Making Changes:
- NEVER make code changes or file modifications unless explicitly instructed by the user
- When the user asks for suggestions or improvements, DESCRIBE what you would change without implementing it
- Only implement changes when the user gives explicit approval (e.g., "do it", "implement that", "make the change")
- If unsure whether to implement or just suggest, always ask first

Testing after code changes:
- After editing code files (not comments, README, or documentation), ALWAYS test the changes using execute_bash
- Run appropriate build/test commands based on the project type:
  * Rust: 'cargo build' and/or 'cargo test'
  * JavaScript/TypeScript: 'npm run build' and/or 'npm test'
  * Python: 'python -m pytest' or 'python -m unittest'
  * Go: 'go build' and/or 'go test'
- If tests fail, fix the errors and test again
- Do NOT run tests for changes to: comments only, README.md, documentation files, or configuration files

Your goal is to help users with coding tasks efficiently and accurately.
Always use the metric system for all measurements. If the user uses other units, convert them and answer in metric.
Show imperial units only when the user explicitly asks for them."#,
            features.join("\n"),
            edit_instruction
        );

        // Append custom instructions if provided
        if let Some(instructions) = custom_instructions {
            system_text.push_str("\n\n");
            system_text.push_str(&instructions);
        }

        Self {
            messages: Vec::new(),
            system_prompt: vec![SystemPrompt::new_cached_with_ttl(
                system_text.to_string(),
                None,
            )],
            config: SofosConfig::default(),
        }
    }

    /// Estimate token count for a string
    pub fn estimate_tokens(text: &str) -> usize {
        // Conservative: 1 token per 3.5 chars (accounts for code/JSON being token-heavy)
        (text.len() as f64 / 3.5).ceil() as usize
    }

    /// Estimate total tokens in system prompt
    fn estimate_system_tokens(&self) -> usize {
        self.system_prompt
            .iter()
            .map(|sp| Self::estimate_tokens(&sp.text))
            .sum()
    }

    /// Estimate tokens for a single message
    fn estimate_message_tokens(msg: &Message) -> usize {
        use crate::api::{MessageContent, MessageContentBlock};

        match &msg.content {
            MessageContent::Text { content } => Self::estimate_tokens(content),
            MessageContent::Blocks { content } => content
                .iter()
                .map(|block| match block {
                    MessageContentBlock::Text { text, .. } => Self::estimate_tokens(text),
                    MessageContentBlock::Thinking {
                        thinking,
                        signature,
                        ..
                    } => Self::estimate_tokens(thinking) + Self::estimate_tokens(signature) + 10,
                    MessageContentBlock::Summary { summary, .. } => {
                        Self::estimate_tokens(summary) + 10
                    }
                    MessageContentBlock::ToolUse {
                        id, name, input, ..
                    } => {
                        let input_str = serde_json::to_string(input).unwrap_or_default();
                        Self::estimate_tokens(id)
                            + Self::estimate_tokens(name)
                            + Self::estimate_tokens(&input_str)
                            + 10
                    }
                    MessageContentBlock::ToolResult {
                        tool_use_id,
                        content,
                        ..
                    } => Self::estimate_tokens(tool_use_id) + Self::estimate_tokens(content) + 10,
                    MessageContentBlock::ServerToolUse {
                        id, name, input, ..
                    } => {
                        let input_str = serde_json::to_string(input).unwrap_or_default();
                        Self::estimate_tokens(id)
                            + Self::estimate_tokens(name)
                            + Self::estimate_tokens(&input_str)
                            + 10
                    }
                    MessageContentBlock::WebSearchToolResult {
                        tool_use_id,
                        content,
                        ..
                    } => {
                        let content_str = serde_json::to_string(content).unwrap_or_default();
                        Self::estimate_tokens(tool_use_id)
                            + Self::estimate_tokens(&content_str)
                            + 20
                    }
                    MessageContentBlock::Image { source, .. } => {
                        // Images are tokenized based on pixel dimensions
                        // Estimate ~1000 tokens per image (typical for medium-sized images)
                        // Actual formula: tokens = (width * height) / 750
                        match source {
                            crate::api::ImageSource::Base64 { data, .. } => {
                                // Rough estimate based on base64 data size
                                // Base64 encodes 3 bytes into 4 chars, so decode estimate
                                let estimated_bytes = data.len() * 3 / 4;
                                // Assume typical compression, estimate pixels
                                // Very rough: ~10 bytes per pixel after compression
                                let estimated_pixels = estimated_bytes / 10;
                                (estimated_pixels / 750).max(100)
                            }
                            crate::api::ImageSource::Url { .. } => {
                                // Can't know size without fetching; assume medium image
                                1000
                            }
                        }
                    }
                })
                .sum(),
        }
    }

    /// Calculate total estimated tokens for current conversation
    pub fn estimate_total_tokens(&self) -> usize {
        let system_tokens = self.estimate_system_tokens();
        let message_tokens: usize = self
            .messages
            .iter()
            .map(|m| Self::estimate_message_tokens(m))
            .sum();

        system_tokens + message_tokens
    }

    /// Trim messages to stay within token budget
    fn trim_if_needed(&mut self) {
        if self.messages.len() > self.config.max_messages {
            let remove_count = self.messages.len() - self.config.max_messages;
            self.messages.drain(0..remove_count);
        }

        let mut total_tokens = self.estimate_total_tokens();

        while total_tokens > self.config.max_context_tokens && self.messages.len() > 10 {
            let removed_tokens = Self::estimate_message_tokens(&self.messages[0]);
            self.messages.remove(0);
            total_tokens -= removed_tokens;
        }

        if total_tokens > self.config.max_context_tokens && self.messages.len() <= 10 {
            eprintln!(
                "⚠️  Warning: Conversation approaching token limit ({} tokens). Consider starting a new session.",
                total_tokens
            );
        }
    }

    /// Check if conversation needs compaction (token usage > trigger ratio)
    pub fn needs_compaction(&self) -> bool {
        let threshold =
            (self.config.max_context_tokens as f64 * self.config.compaction_trigger_ratio) as usize;
        self.estimate_total_tokens() > threshold
    }

    /// Find a clean split point for compaction, keeping at least `preserve_recent` messages.
    /// Returns the index where "recent" messages start (split on user-message boundary).
    pub fn compaction_split_point(&self) -> usize {
        let preserve = self.config.compaction_preserve_recent;
        if self.messages.len() <= preserve + 5 {
            return 0;
        }

        let mut split = self.messages.len().saturating_sub(preserve);

        // Walk backward to land on a user-role message boundary
        while split > 0 && self.messages[split].role != "user" {
            split -= 1;
        }
        // Avoid orphaning tool results: if this user message contains tool_result blocks,
        // walk back further to include the preceding assistant tool_use
        while split > 0 {
            if let crate::api::MessageContent::Blocks { content } = &self.messages[split].content {
                let has_tool_result = content.iter().any(|b| {
                    matches!(
                        b,
                        crate::api::MessageContentBlock::ToolResult { .. }
                            | crate::api::MessageContentBlock::WebSearchToolResult { .. }
                    )
                });
                if has_tool_result {
                    split -= 1;
                    continue;
                }
            }
            break;
        }

        split
    }

    /// Truncate large tool results in messages[0..up_to] to save tokens cheaply.
    pub fn truncate_tool_results(&mut self, up_to: usize) {
        let threshold = self.config.tool_result_truncate_threshold;
        let keep_chars = 500;

        for msg in self.messages[..up_to].iter_mut() {
            if let crate::api::MessageContent::Blocks { content } = &mut msg.content {
                for block in content.iter_mut() {
                    if let crate::api::MessageContentBlock::ToolResult {
                        content: result_text,
                        ..
                    } = block
                    {
                        if result_text.len() > threshold {
                            let original_len = result_text.len();
                            let actual_keep = keep_chars.min(original_len / 3);
                            let start = &result_text[..actual_keep];
                            let end = &result_text[result_text.len() - actual_keep..];
                            *result_text = format!(
                                "{}\n...[truncated {} chars]...\n{}",
                                start, original_len, end
                            );
                        }
                    }
                }
            }
        }
    }

    /// Serialize older messages into a text representation for the summarization prompt.
    pub fn serialize_messages_for_summary(messages: &[Message]) -> String {
        let mut parts = Vec::new();

        for msg in messages {
            let role_label = if msg.role == "user" {
                "User"
            } else {
                "Assistant"
            };

            match &msg.content {
                crate::api::MessageContent::Text { content } => {
                    parts.push(format!("{}: {}", role_label, content));
                }
                crate::api::MessageContent::Blocks { content } => {
                    for block in content {
                        match block {
                            crate::api::MessageContentBlock::Text { text, .. } => {
                                parts.push(format!("{}: {}", role_label, text));
                            }
                            crate::api::MessageContentBlock::ToolUse { name, input, .. } => {
                                let input_str = serde_json::to_string(input).unwrap_or_default();
                                let input_preview = if input_str.len() > 200 {
                                    format!("{}...", &input_str[..200])
                                } else {
                                    input_str
                                };
                                parts.push(format!("[Tool call: {}({})]", name, input_preview));
                            }
                            crate::api::MessageContentBlock::ToolResult { content, .. } => {
                                let preview = if content.len() > 300 {
                                    format!("{}...", &content[..300])
                                } else {
                                    content.clone()
                                };
                                parts.push(format!("[Tool result: {}]", preview));
                            }
                            crate::api::MessageContentBlock::Image { .. } => {
                                parts.push("[Image attached]".to_string());
                            }
                            // Skip thinking, summary, server tool use, web search results
                            _ => {}
                        }
                    }
                }
            }
        }

        parts.join("\n\n")
    }

    /// Replace messages[0..split_point] with a single summary message.
    pub fn replace_with_summary(&mut self, summary: String, split_point: usize) {
        if split_point == 0 || split_point > self.messages.len() {
            return;
        }
        self.messages.drain(0..split_point);
        let summary_msg = Message::user(format!(
            "[Conversation Summary]\n\nThe following is a summary of our earlier conversation:\n\n{}",
            summary
        ));
        self.messages.insert(0, summary_msg);
    }

    /// Fallback trim used when compaction fails
    pub fn fallback_trim(&mut self) {
        self.trim_if_needed();
    }

    pub fn add_user_message(&mut self, content: String) {
        self.messages.push(Message::user(content));
        self.trim_if_needed();
    }

    /// Add a user message with content blocks (text and/or images)
    pub fn add_user_with_blocks(&mut self, blocks: Vec<crate::api::MessageContentBlock>) {
        self.messages.push(Message::user_with_blocks(blocks));
        self.trim_if_needed();
    }

    pub fn add_assistant_with_blocks(&mut self, blocks: Vec<crate::api::MessageContentBlock>) {
        self.messages.push(Message::assistant_with_blocks(blocks));
        self.trim_if_needed();
    }

    pub fn add_tool_results(&mut self, results: Vec<crate::api::MessageContentBlock>) {
        self.messages.push(Message::user_with_tool_results(results));
        self.trim_if_needed();
    }

    pub fn messages(&self) -> &[Message] {
        &self.messages
    }

    pub fn system_prompt(&self) -> &Vec<SystemPrompt> {
        &self.system_prompt
    }

    pub fn clear(&mut self) {
        self.messages.clear();
    }

    pub fn restore_messages(&mut self, messages: Vec<Message>) {
        self.messages = messages;
        self.trim_if_needed();
    }

    /// Remove the last message from the conversation (used for error recovery)
    pub fn remove_last_message(&mut self) {
        self.messages.pop();
    }

    pub fn _len(&self) -> usize {
        self.messages.len()
    }

    pub fn _is_empty(&self) -> bool {
        self.messages.is_empty()
    }
}

impl Default for ConversationHistory {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_message_limit_trimming() {
        let mut history = ConversationHistory::new();

        for i in 0..510 {
            history.add_user_message(format!("Message {}", i));
        }

        assert_eq!(history.messages().len(), 500);

        if let crate::api::MessageContent::Text { content } = &history.messages()[0].content {
            assert_eq!(content, "Message 10");
        }
    }

    #[test]
    fn test_message_limit_with_blocks() {
        let mut history = ConversationHistory::new();

        for i in 0..260 {
            history.add_user_message(format!("User {}", i));
            history.add_assistant_with_blocks(vec![MessageContentBlock::Text {
                text: format!("Assistant {}", i),
                cache_control: None,
            }]);
        }

        assert_eq!(history.messages().len(), 500);
    }

    #[test]
    fn test_no_trimming_below_limit() {
        let mut history = ConversationHistory::new();

        for i in 0..20 {
            history.add_user_message(format!("Message {}", i));
        }

        assert_eq!(history.messages().len(), 20);
    }

    #[test]
    fn test_token_limit_trimming() {
        let mut history = ConversationHistory::new();
        history.config.max_context_tokens = 5000;

        // ~1000 chars = ~286 tokens; system prompt ~857 tokens; need enough to exceed 5000
        let large_content = "x".repeat(1000);

        for i in 0..20 {
            history.add_user_message(format!("{} {}", i, large_content));
        }

        assert!(history.messages().len() < 20);
        assert!(history.messages().len() >= 10);

        if let crate::api::MessageContent::Text { content } = &history.messages()[0].content {
            assert!(!content.starts_with("0 "));
        }
    }

    #[test]
    fn test_token_estimation() {
        // 35 chars = 10 tokens at 3.5 chars/token
        let tokens = ConversationHistory::estimate_tokens("12345678901234567890123456789012345");
        assert_eq!(tokens, 10);

        let tokens = ConversationHistory::estimate_tokens("");
        assert_eq!(tokens, 0);
    }

    #[test]
    fn test_needs_compaction() {
        let mut history = ConversationHistory::new();
        // Use a large token limit so the system prompt alone doesn't trigger it
        history.config.max_context_tokens = 100_000;
        history.config.compaction_trigger_ratio = 0.80;

        // Should not need compaction with small messages
        history.add_user_message("hello".to_string());
        assert!(!history.needs_compaction());

        // Add enough messages to exceed 80% of 100k
        let large_content = "x".repeat(10_000);
        for _ in 0..30 {
            history.messages.push(Message::user(large_content.clone()));
        }
        assert!(history.needs_compaction());
    }

    #[test]
    fn test_compaction_split_point() {
        let mut history = ConversationHistory::new();
        history.config.compaction_preserve_recent = 4;

        for i in 0..10 {
            history.messages.push(Message::user(format!("msg {}", i)));
        }

        let split = history.compaction_split_point();
        assert_eq!(split, 6); // 10 - 4 = 6
    }

    #[test]
    fn test_compaction_split_too_few_messages() {
        let mut history = ConversationHistory::new();
        history.config.compaction_preserve_recent = 20;

        for i in 0..10 {
            history.messages.push(Message::user(format!("msg {}", i)));
        }

        let split = history.compaction_split_point();
        assert_eq!(split, 0); // not enough to compact
    }

    #[test]
    fn test_truncate_tool_results() {
        let mut history = ConversationHistory::new();
        history.config.tool_result_truncate_threshold = 100;

        let large_content = "x".repeat(500);
        history.messages.push(Message::user_with_tool_results(vec![
            MessageContentBlock::ToolResult {
                tool_use_id: "id1".to_string(),
                content: large_content,
                cache_control: None,
            },
        ]));

        history.truncate_tool_results(1);

        if let crate::api::MessageContent::Blocks { content } = &history.messages()[0].content {
            if let MessageContentBlock::ToolResult { content, .. } = &content[0] {
                assert!(content.contains("truncated"));
                assert!(content.len() < 500); // keep 500/3=166 each side + marker < 500
            } else {
                panic!("Expected ToolResult");
            }
        } else {
            panic!("Expected Blocks");
        }
    }

    #[test]
    fn test_replace_with_summary() {
        let mut history = ConversationHistory::new();

        for i in 0..10 {
            history.messages.push(Message::user(format!("msg {}", i)));
        }

        history.replace_with_summary("This is the summary".to_string(), 7);

        // 7 removed, 1 summary inserted, 3 remaining = 4
        assert_eq!(history.messages().len(), 4);

        if let crate::api::MessageContent::Text { content } = &history.messages()[0].content {
            assert!(content.contains("Conversation Summary"));
            assert!(content.contains("This is the summary"));
        }
    }

    #[test]
    fn test_serialize_messages_for_summary() {
        let messages = vec![
            Message::user("Hello, help me with code".to_string()),
            Message::assistant_with_blocks(vec![MessageContentBlock::Text {
                text: "Sure, let me look at the files.".to_string(),
                cache_control: None,
            }]),
        ];

        let serialized = ConversationHistory::serialize_messages_for_summary(&messages);
        assert!(serialized.contains("User: Hello, help me with code"));
        assert!(serialized.contains("Assistant: Sure, let me look at the files."));
    }
}