sofos 0.2.11

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
//! Single-turn driver: takes one user message (plus any pasted or
//! referenced images), kicks off the initial API request, and hands the
//! response off to [`crate::repl::ResponseHandler`] for the tool loop.
//! Also owns the image-error retry path that strips images from the
//! conversation and retries once before surfacing the failure.

use crate::api::{ImageSource, MessageContentBlock};
use crate::error::{Result, SofosError};
use crate::repl::{Repl, ResponseHandler};
use crate::session::DisplayMessage;
use crate::tools::image::{ImageReference, extract_image_references};
use crate::ui::UI;
use colored::Colorize;
use std::sync::Arc;
use std::time::Instant;

impl Repl {
    pub fn process_message(
        &mut self,
        user_input: &str,
        pasted_images: Vec<crate::clipboard::PastedImage>,
    ) -> Result<()> {
        // Record turn start so we can show "Finished in Xs" when the
        // model is fully done (after every text reply, tool call, and
        // continuation). Steer messages typed mid-turn don't reset
        // this — they're folded into the same turn via `SteerBuffer` and
        // the same `process_message` call keeps running until the
        // agent loop exits.
        let turn_start = Instant::now();
        let (remaining_text, image_refs) = extract_image_references(user_input);

        let has_images = !image_refs.is_empty() || !pasted_images.is_empty();

        if !image_refs.is_empty() {
            println!(
                "{} Detected {} image reference(s)",
                "🔍".bright_cyan(),
                image_refs.len()
            );
        }

        let content_blocks = if has_images {
            let mut blocks: Vec<MessageContentBlock> = Vec::new();

            for pasted in &pasted_images {
                blocks.push(MessageContentBlock::Image {
                    source: ImageSource::Base64 {
                        media_type: pasted.media_type.clone(),
                        data: pasted.base64_data.clone(),
                    },
                    cache_control: None,
                });
            }
            let mut failed_images: Vec<String> = Vec::new();

            // Load images first (Claude recommends images before text)
            for img_ref in &image_refs {
                match self.image_loader.load_image(img_ref) {
                    Ok(source) => {
                        let api_source = match source {
                            crate::tools::image::ImageSource::Base64 { media_type, data } => {
                                ImageSource::Base64 { media_type, data }
                            }
                            crate::tools::image::ImageSource::Url { url } => {
                                ImageSource::Url { url }
                            }
                        };
                        blocks.push(MessageContentBlock::Image {
                            source: api_source,
                            cache_control: None,
                        });

                        let path_str = match img_ref {
                            ImageReference::LocalPath(p) => format!("local: {}", p),
                            ImageReference::WebUrl(u) => format!("url: {}", u),
                        };
                        println!("{} {}", "📷 Image loaded:".bright_cyan(), path_str.dimmed());
                    }
                    Err(e) => {
                        let path_str = match img_ref {
                            ImageReference::LocalPath(p) => p.clone(),
                            ImageReference::WebUrl(u) => u.clone(),
                        };
                        let error_msg = format!("[Failed to load image '{}': {}]", path_str, e);
                        failed_images.push(error_msg);
                        println!(
                            "\n{} {}\n",
                            "⚠️  Failed to load image:".bright_yellow().bold(),
                            e
                        );
                    }
                }
            }

            let mut text_parts: Vec<String> = Vec::new();

            if !remaining_text.trim().is_empty() {
                text_parts.push(remaining_text.clone());
            }

            if !failed_images.is_empty() {
                text_parts.extend(failed_images);
            }

            if !text_parts.is_empty() {
                blocks.push(MessageContentBlock::Text {
                    text: text_parts.join("\n\n"),
                    cache_control: None,
                });
            } else if blocks.is_empty() {
                return Err(SofosError::ToolExecution(
                    "No valid images or text in message".to_string(),
                ));
            }

            Some(blocks)
        } else {
            None
        };

        if let Some(blocks) = content_blocks {
            self.session_state.conversation.add_user_with_blocks(blocks);
        } else {
            self.session_state
                .conversation
                .add_user_message(user_input.to_string());
        }

        self.session_state
            .display_messages
            .push(DisplayMessage::UserMessage {
                content: user_input.to_string(),
            });

        if self.session_state.conversation.needs_compaction() {
            // Inner failure paths already surface a warning through
            // `UI::print_warning` and fall back to `fallback_trim`,
            // so the user is never left without compaction. The
            // outer `Err` arm is only reachable from future failure
            // modes added to the helper, but log it through tracing
            // rather than swallowing it silently.
            if let Err(e) = self.compact_conversation(false) {
                tracing::warn!(error = %e, "auto-compaction returned an error");
            }
        }

        let initial_request = self.build_initial_request();

        let runtime = &self.runtime;

        let client_for_retry = self.client.clone();

        let response_result: Result<_> = {
            let printer = Arc::new(crate::ui::StreamPrinter::new());
            let p_text = printer.clone();
            let p_think = printer.clone();
            let interrupt = Arc::clone(&self.interrupt_flag);

            let client = self.client.clone();
            let req = initial_request;
            let result = runtime.block_on(async move {
                client
                    .create_message_streaming(
                        req,
                        move |t| p_text.on_text_delta(t),
                        move |t| p_think.on_thinking_delta(t),
                        interrupt,
                    )
                    .await
            });

            printer.finish();
            result
        };

        // Handle API errors, especially those related to invalid images
        let response = match response_result {
            Ok(resp) => resp,
            Err(e) => {
                // Try to recover from an image-loading 400 by stripping every
                // image block from the conversation and retrying once.
                if let SofosError::Api(ref msg) = e {
                    let is_400_error = msg.contains("400");
                    let is_image_error = msg.contains("Unable to download")
                        || msg.contains("invalid_request_error")
                        || msg.contains("verify the URL");

                    let current_has_images = !image_refs.is_empty();
                    let conversation_has_images =
                        self.session_state.conversation.messages().iter().any(|m| {
                            use crate::api::{MessageContent, MessageContentBlock};
                            if let MessageContent::Blocks { content } = &m.content {
                                content
                                    .iter()
                                    .any(|b| matches!(b, MessageContentBlock::Image { .. }))
                            } else {
                                false
                            }
                        });
                    let has_images = current_has_images || conversation_has_images;

                    if is_400_error && is_image_error && has_images {
                        println!(
                            "\n{} One or more image URLs in the conversation could not be loaded by the API\n",
                            "⚠️  Image loading error:".bright_yellow().bold()
                        );

                        // Strip every Image block in place. Surrounding text
                        // survives so the user's actual prompt isn't lost on
                        // the retry. A message that was image-only gets
                        // dropped entirely.
                        let mut cleaned_messages: Vec<crate::api::Message> = Vec::new();
                        for m in self.session_state.conversation.messages() {
                            use crate::api::{Message, MessageContent, MessageContentBlock};
                            let cleaned = match &m.content {
                                MessageContent::Blocks { content } => {
                                    let filtered: Vec<MessageContentBlock> = content
                                        .iter()
                                        .filter(|b| !matches!(b, MessageContentBlock::Image { .. }))
                                        .cloned()
                                        .collect();
                                    if filtered.is_empty() {
                                        continue;
                                    }
                                    Message {
                                        role: m.role.clone(),
                                        content: MessageContent::Blocks { content: filtered },
                                    }
                                }
                                _ => m.clone(),
                            };
                            cleaned_messages.push(cleaned);
                        }

                        self.session_state.conversation.clear();
                        self.session_state
                            .conversation
                            .restore_messages(cleaned_messages);

                        let system_note = if !image_refs.is_empty() {
                            "[SYSTEM ERROR: Image URLs in your message could not be loaded and have been removed from the conversation.]"
                        } else {
                            "[SYSTEM ERROR: Image URLs from a previous message could not be loaded and have been removed from the conversation. You can continue normally.]"
                        };
                        if !self
                            .session_state
                            .conversation
                            .append_text_to_last_user_blocks(system_note.to_string())
                        {
                            self.session_state
                                .conversation
                                .add_user_message(system_note.to_string());
                        }

                        // Backup the cleaned state so a retry failure
                        // restores the image-free conversation rather than
                        // the image-laden one that caused the 400.
                        let conversation_backup =
                            self.session_state.conversation.messages().to_vec();

                        let new_request = self.build_initial_request();

                        println!("{}", "Retrying request without images...".dimmed());
                        println!();

                        // Stream the retry with the same interrupt support
                        // as the initial request so ESC works during the
                        // second attempt.
                        let printer = Arc::new(crate::ui::StreamPrinter::new());
                        let p_text = printer.clone();
                        let p_think = printer.clone();
                        let interrupt = Arc::clone(&self.interrupt_flag);
                        let client = client_for_retry.clone();
                        let req = new_request;
                        let retry_result = runtime.block_on(async move {
                            client
                                .create_message_streaming(
                                    req,
                                    move |t| p_text.on_text_delta(t),
                                    move |t| p_think.on_thinking_delta(t),
                                    interrupt,
                                )
                                .await
                        });
                        printer.finish();

                        match retry_result {
                            Ok(resp) => resp,
                            Err(retry_err) => {
                                self.session_state.conversation.clear();
                                self.session_state
                                    .conversation
                                    .restore_messages(conversation_backup);
                                let failure_note = format!(
                                    "[SYSTEM ERROR: Image loading failed and the retry also failed: {}.]",
                                    retry_err
                                );
                                if !self
                                    .session_state
                                    .conversation
                                    .append_text_to_last_user_blocks(failure_note.clone())
                                {
                                    self.session_state
                                        .conversation
                                        .add_user_message(failure_note);
                                }
                                return Err(retry_err);
                            }
                        }
                    } else {
                        // Non-image API error. Append a system note to the
                        // user turn that triggered the failure rather than
                        // fabricating an assistant turn (which would make
                        // the model think it wrote the error string on the
                        // next turn).
                        let note = format!(
                            "[SYSTEM ERROR: API error: {}. The request did not produce a response.]",
                            msg
                        );
                        if !self
                            .session_state
                            .conversation
                            .append_text_to_last_user_blocks(note.clone())
                        {
                            self.session_state.conversation.add_user_message(note);
                        }
                        return Err(e);
                    }
                } else {
                    // Non-API error (transport, IO, ...). Same approach as
                    // the non-image API branch.
                    let note = format!(
                        "[SYSTEM ERROR: {}. The request did not produce a response.]",
                        e
                    );
                    if !self
                        .session_state
                        .conversation
                        .append_text_to_last_user_blocks(note.clone())
                    {
                        self.session_state.conversation.add_user_message(note);
                    }
                    return Err(e);
                }
            }
        };

        self.session_state.add_usage(&response.usage);

        let mut handler = ResponseHandler::new(
            self.client.clone(),
            self.tool_executor.clone(),
            self.session_state.conversation.clone(),
            self.model_config.model.clone(),
            self.model_config.max_tokens,
            self.model_config.reasoning_effort,
            self.available_tools.clone(),
            Arc::clone(&self.interrupt_flag),
            Arc::clone(&self.steer_buffer),
            self.session_state.session_id.clone(),
        );

        let result = runtime.block_on(handler.handle_response(
            response.content,
            &mut self.session_state.display_messages,
            &mut self.session_state.total_input_tokens,
            &mut self.session_state.total_output_tokens,
            &mut self.session_state.total_cache_read_tokens,
            &mut self.session_state.total_cache_creation_tokens,
            &mut self.session_state.peak_single_turn_input_tokens,
        ));

        // Always preserve conversation state so the AI retains context on retry
        self.session_state.conversation = handler.conversation().clone();

        match result {
            Ok(_) => {
                println!(
                    "{}",
                    UI::format_turn_finished(turn_start.elapsed()).dimmed()
                );
                Ok(())
            }
            Err(SofosError::Interrupted) => Ok(()),
            Err(e) => {
                // Add error context so the AI knows what happened on next turn.
                // Check last message role to maintain proper alternation —
                // the conversation could end on either role depending on where
                // the error occurred (e.g. after assistant reasoning vs after tool results).
                let error_text = format!(
                    "[System error during processing: {}. Previous actions are preserved above.]",
                    e
                );
                let last_role = self
                    .session_state
                    .conversation
                    .messages()
                    .last()
                    .map(|m| m.role.as_str());
                if last_role == Some("assistant") {
                    // Last message is assistant — add user error context
                    self.session_state.conversation.add_user_message(error_text);
                } else {
                    // Last message is user (tool results) or empty — add assistant error context
                    self.session_state
                        .conversation
                        .add_assistant_with_blocks(vec![crate::api::MessageContentBlock::Text {
                            text: error_text,
                            cache_control: None,
                        }]);
                }
                Err(e)
            }
        }
    }
}