sage-cli 0.9.0

Command-line interface for Sage Agent
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
//! Executor logic for rnk app

use super::state::{SharedState, UiCommand};
use super::theme::current_theme;
use crate::commands::unified::slash_commands::{process_slash_command, SlashCommandAction};
use crate::console::CliConsole;
use rnk::prelude::*;
use sage_core::agent::{ExecutionMode, ExecutionOptions, UnifiedExecutor};
use sage_core::config::load_config;
use sage_core::error::SageResult;
use sage_core::input::InputChannel;
use sage_core::interrupt::{interrupt_current_task, reset_global_interrupt_manager, InterruptReason};
use sage_core::output::OutputMode;
use sage_core::types::TaskMetadata;
use sage_core::ui::bridge::state::ExecutionPhase;
use sage_core::ui::bridge::AgentEvent;
use sage_core::ui::traits::UiContext;
use sage_tools::get_default_tools;
use tokio::sync::mpsc;
use tokio::time::{sleep, Duration};
use unicode_width::UnicodeWidthStr;

/// Handle resume command
async fn handle_resume(
    executor: &mut UnifiedExecutor,
    session_id: Option<&str>,
) -> SageResult<String> {
    let session_id = match session_id {
        Some(id) => id.to_string(),
        None => {
            // Get most recent session
            match executor.get_most_recent_session().await? {
                Some(metadata) => metadata.id,
                None => {
                    return Err(sage_core::error::SageError::config(
                        "No previous sessions found. Start a new session first.",
                    ));
                }
            }
        }
    };

    // Restore the session
    let restored_messages = executor.restore_session(&session_id).await?;
    Ok(format!(
        "Session {} restored ({} messages)",
        session_id, restored_messages.len()
    ))
}

/// Create executor with default configuration
pub async fn create_executor(ui_context: Option<UiContext>) -> SageResult<UnifiedExecutor> {
    let config = load_config()?;
    let working_dir = std::env::current_dir().unwrap_or_default();
    let mode = ExecutionMode::interactive();
    let options = ExecutionOptions::default()
        .with_mode(mode)
        .with_working_directory(&working_dir);

    let mut executor = UnifiedExecutor::with_options(config, options)?;

    // Set UI context for event handling
    if let Some(ctx) = ui_context {
        executor.set_ui_context(ctx);
    }

    executor.set_output_mode(OutputMode::Rnk);
    executor.register_tools(get_default_tools());
    let _ = executor.init_subagent_support();
    Ok(executor)
}

/// Executor loop in background - processes commands and runs tasks
pub async fn executor_loop(
    state: SharedState,
    mut rx: mpsc::Receiver<UiCommand>,
    input_channel: InputChannel,
    ui_context: UiContext,
) {
    // Clone ui_context for event emission, pass original to executor
    let event_ctx = ui_context.clone();

    // Create executor with UI context
    let mut executor = match create_executor(Some(ui_context)).await {
        Ok(e) => e,
        Err(e) => {
            rnk::println(
                Text::new(format!("Failed to create executor: {}", e))
                    .color(Color::Red)
                    .into_element(),
            );
            state.write().should_quit = true;
            rnk::request_render();
            return;
        }
    };
    executor.set_input_channel(input_channel);

    // Process commands
    while let Some(cmd) = rx.recv().await {
        match cmd {
            UiCommand::Submit(task) => {
                let working_dir = std::env::current_dir().unwrap_or_default();
                let console = CliConsole::new(false);

                // Process slash commands first
                let prompt = match process_slash_command(&task, &console, &working_dir).await {
                    Ok(SlashCommandAction::Prompt(p)) => p,
                    Ok(SlashCommandAction::Handled) => {
                        // Command was handled locally, no LLM needed
                        rnk::request_render();
                        continue;
                    }
                    Ok(SlashCommandAction::HandledWithOutput(output)) => {
                        // Command was handled locally with output to display
                        // Print each line separately to avoid rnk layout issues
                        for line in output.lines() {
                            rnk::println(
                                Text::new(line).color(Color::White).into_element(),
                            );
                        }
                        rnk::request_render();
                        continue;
                    }
                    Ok(SlashCommandAction::SetOutputMode(mode)) => {
                        executor.set_output_mode(mode);
                        rnk::println(
                            Text::new(format!("Output mode set to {:?}", mode))
                                .color(Color::Cyan)
                                .dim()
                                .into_element(),
                        );
                        rnk::request_render();
                        continue;
                    }
                    Ok(SlashCommandAction::Resume { session_id }) => {
                        // Handle resume command
                        {
                            let mut s = state.write();
                            s.is_busy = true;
                            s.status_text = "Resuming session...".to_string();
                        }
                        rnk::request_render();

                        let result = handle_resume(&mut executor, session_id.as_deref()).await;

                        {
                            let mut s = state.write();
                            s.is_busy = false;
                            s.status_text.clear();
                        }

                        match result {
                            Ok(msg) => {
                                rnk::println(
                                    Text::new(format!("✓ {}", msg))
                                        .color(Color::Green)
                                        .into_element(),
                                );
                            }
                            Err(e) => {
                                rnk::println(
                                    Text::new(format!("✗ Resume failed: {}", e))
                                        .color(Color::Red)
                                        .into_element(),
                                );
                            }
                        }
                        rnk::request_render();
                        continue;
                    }
                    Ok(SlashCommandAction::SwitchModel { model }) => {
                        // Try to switch model dynamically
                        match executor.switch_model(&model) {
                            Ok(_) => {
                                rnk::println(
                                    Text::new(format!("✓ Switched to model: {}", model))
                                        .color(Color::Green)
                                        .into_element(),
                                );
                            }
                            Err(e) => {
                                rnk::println(
                                    Text::new(format!("✗ Failed to switch model: {}", e))
                                        .color(Color::Red)
                                        .into_element(),
                                );
                            }
                        }
                        rnk::request_render();
                        continue;
                    }
                    Ok(SlashCommandAction::Doctor) => {
                        // Run diagnostics
                        {
                            let mut s = state.write();
                            s.is_busy = true;
                            s.status_text = "Running diagnostics...".to_string();
                        }
                        rnk::request_render();

                        // Run doctor command
                        let result = crate::commands::diagnostics::doctor("sage_config.json").await;

                        {
                            let mut s = state.write();
                            s.is_busy = false;
                            s.status_text.clear();
                        }

                        if let Err(e) = result {
                            rnk::println(
                                Text::new(format!("Diagnostics failed: {}", e))
                                    .color(Color::Red)
                                    .into_element(),
                            );
                        }
                        rnk::request_render();
                        continue;
                    }
                    Ok(SlashCommandAction::Exit) => {
                        state.write().should_quit = true;
                        rnk::request_render();
                        break;
                    }
                    Err(e) => {
                        rnk::println(
                            Text::new(format!("Command error: {}", e))
                                .color(Color::Red)
                                .into_element(),
                        );
                        rnk::request_render();
                        continue;
                    }
                };

                {
                    let mut s = state.write();
                    s.is_busy = true;
                    s.status_text = "Thinking...".to_string();
                }
                rnk::request_render();

                // Reset interrupt manager for new task
                reset_global_interrupt_manager();

                event_ctx.emit(AgentEvent::UserInputReceived { input: prompt.clone() });
                event_ctx.emit(AgentEvent::ThinkingStarted);

                // Execute task
                let working_dir_str = working_dir.to_string_lossy().to_string();
                let task_meta = TaskMetadata::new(&prompt, &working_dir_str);

                match executor.execute(task_meta).await {
                    Ok(_) => {}
                    Err(e) => {
                        event_ctx.emit(AgentEvent::error("execution", e.to_string()));
                    }
                }

                {
                    let mut s = state.write();
                    s.is_busy = false;
                    s.status_text.clear();
                }
                rnk::request_render();
            }
            UiCommand::Cancel => {
                // Actually cancel the running task through interrupt manager
                interrupt_current_task(InterruptReason::UserInterrupt);

                event_ctx.emit(AgentEvent::ThinkingStopped);
                rnk::println(
                    Text::new("⦻ Cancelled")
                        .color(Color::Yellow)
                        .dim()
                        .into_element(),
                );
                {
                    let mut s = state.write();
                    s.is_busy = false;
                    s.status_text.clear();
                }
                rnk::request_render();
            }
            UiCommand::Quit => {
                state.write().should_quit = true;
                rnk::request_render();
                break;
            }
        }
    }
}

/// Background thread logic for printing messages and updating UI
pub async fn background_loop(
    state: SharedState,
    adapter: sage_core::ui::bridge::EventAdapter,
) {
    use super::components::{format_message, format_tool_start, render_error};

    let theme = current_theme();

    // Print header banner with border (Claude Code style)
    let version = env!("CARGO_PKG_VERSION");
    let (model, provider, working_dir) = {
        let ui_state = state.read();
        (
            ui_state.session.model.clone(),
            ui_state.session.provider.clone(),
            ui_state.session.working_dir.clone(),
        )
    };

    // Calculate box width based on content
    let title_line = format!("  â—† Sage v{}", version);
    let model_line = format!("    {} · {}", model, provider);
    let dir_line = format!("    {}", working_dir);
    let content_width = [&title_line, &model_line, &dir_line]
        .iter()
        .map(|s| s.width())
        .max()
        .unwrap_or(40);
    let box_width = content_width + 4; // padding

    let top_border = format!("╭{}╮", "─".repeat(box_width));
    let bottom_border = format!("╰{}╯", "─".repeat(box_width));

    // Helper to pad line to box width
    let pad_line = |s: &str| -> String {
        let w = s.width();
        let padding = box_width.saturating_sub(w);
        format!("│{}{}│", s, " ".repeat(padding))
    };

    rnk::println(Text::new("").into_element());
    rnk::println(
        Text::new(&top_border)
            .color(theme.border_subtle)
            .into_element(),
    );
    rnk::println(
        Text::new(pad_line(&title_line))
            .color(theme.border_subtle)
            .into_element(),
    );
    rnk::println(
        Text::new(pad_line(&model_line))
            .color(theme.border_subtle)
            .into_element(),
    );
    rnk::println(
        Text::new(pad_line(&dir_line))
            .color(theme.border_subtle)
            .into_element(),
    );
    rnk::println(
        Text::new(&bottom_border)
            .color(theme.border_subtle)
            .into_element(),
    );
    // Spacing before bottom UI
    rnk::println(Text::new("").into_element());
    rnk::println(Text::new("").into_element());

    loop {
        sleep(Duration::from_millis(80)).await;

        // Check if should quit
        if state.read().should_quit {
            break;
        }

        // Collect data under lock, then process I/O outside lock
        let pending_work = {
            let app_state = adapter.get_state();
            // Use completed messages only (not streaming/temporary messages)
            // This avoids truncation issues where partial messages get printed
            let messages = &app_state.messages;
            let new_count = messages.len();

            let mut ui_state = state.write();

            // Update session info from adapter if changed
            if app_state.session.model != "unknown" && ui_state.session.model == "unknown" {
                ui_state.session.model = app_state.session.model.clone();
                ui_state.session.provider = app_state.session.provider.clone();
                if let Some(ref sid) = app_state.session.session_id {
                    ui_state.session.session_id = Some(sid.clone());
                }
            }

            // Header printing removed - now done in run_rnk_app() before rnk starts

            // Update busy state from adapter - Error state is not busy
            ui_state.is_busy =
                !matches!(app_state.phase, ExecutionPhase::Idle | ExecutionPhase::Error { .. });
            if ui_state.is_busy {
                ui_state.status_text = app_state.status_text();
                // Increment animation frame for spinner
                ui_state.animation_frame = ui_state.animation_frame.wrapping_add(1);
            } else {
                ui_state.status_text.clear();
            }

            // Check for tool execution start - cache tool info to print after messages
            if let Some(ref tool_exec) = app_state.tool_execution {
                let tool_key = format!("{}:{}", tool_exec.tool_name, tool_exec.description);
                if ui_state.current_tool_printed.as_ref() != Some(&tool_key) {
                    // New tool detected, cache it
                    ui_state.pending_tool = Some((tool_exec.tool_name.clone(), tool_exec.description.clone()));
                    ui_state.current_tool_printed = Some(tool_key);
                }
            } else {
                // Tool finished, clear the tracking
                ui_state.current_tool_printed = None;
            }

            // Collect error work
            let error_work = if let ExecutionPhase::Error { ref message } = app_state.phase {
                if !ui_state.error_displayed {
                    ui_state.error_displayed = true;
                    Some(render_error(message, theme))
                } else {
                    None
                }
            } else {
                ui_state.error_displayed = false;
                None
            };

            // Collect new messages - format them while holding lock
            // Skip ToolCall messages - they are printed via pending_tool mechanism
            let (new_messages, pending_tool_to_print) = if new_count > ui_state.printed_count {
                let msgs: Vec<_> = messages
                    .iter()
                    .skip(ui_state.printed_count)
                    .filter(|msg| !matches!(msg.content, sage_core::ui::bridge::state::MessageContent::ToolCall { .. }))
                    .map(|msg| format_message(msg, theme))
                    .collect();
                ui_state.printed_count = new_count;
                // Only take pending tool if there are new text messages
                // This ensures text messages are printed before tool calls
                let pending = if !msgs.is_empty() {
                    ui_state.pending_tool.take()
                } else {
                    None
                };
                (msgs, pending)
            } else {
                (Vec::new(), None)
            };

            (error_work, new_messages, pending_tool_to_print)
        }; // Lock released here

        // Process all I/O outside the lock
        let (error_work, new_messages, pending_tool_to_print) = pending_work;

        // Print new messages first (Assistant response comes before tool call)
        for msg_element in new_messages {
            rnk::println(msg_element);
            rnk::println(""); // Empty line
        }

        // Print pending tool after messages
        if let Some((tool_name, description)) = pending_tool_to_print {
            rnk::println(format_tool_start(&tool_name, &description, theme));
        }

        if let Some(error) = error_work {
            rnk::println(error);
            rnk::println(""); // Empty line
        }

        // Request render to update spinner animation
        rnk::request_render();
    }
}