rho-coding-agent 1.39.0

A lightweight agent harness inspired by Pi
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
use std::{
    collections::VecDeque,
    future::Future,
    path::PathBuf,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    time::{Duration, Instant},
};

use questionnaire::QuestionnaireCancelReason;
use ratatui::DefaultTerminal;
use tokio::sync::oneshot;
mod activity;
mod advisor_command;
mod advisor_status;
mod agent_editor;
mod agent_picker;
mod app_construct;
mod app_state;
mod approval;
pub(crate) mod attachment;
mod background_polls;
mod clipboard;
mod command_actions;
mod command_block;
mod command_palette;
mod compaction_display;
mod composer;
mod composer_attachments;
mod composer_chrome;
mod config_actions;
mod config_editor;
mod config_input;
mod config_picker;
mod context_handoff;
mod copy_interaction;
mod doctor;
pub(crate) mod event_adapter;
mod external_editor;
mod fast_command;
mod feed_image;
mod file_palette;
mod file_picker;
mod first_run;
mod frame_scheduler;
mod goal;
mod line_editor;
mod subagent_inbox;
mod subagent_questionnaires;
mod text_input;

fn plural_suffix(count: usize) -> &'static str {
    if count == 1 {
        ""
    } else {
        "s"
    }
}

pub(crate) use first_run::SetupEntry;
pub(crate) use goal::GOAL_JUDGE_PROMPT;
mod changelog_command;
mod chat_media;
mod choice_actions;
mod claude_login;
mod composer_layout;
mod during_turn;
mod goal_command;
mod help_picker;
mod history_cache;
mod history_soft_settings;
mod hook_actions;
mod info_command;
mod inline_choice;
mod inline_shell;
mod keybindings;
mod keyboard_modes;
mod limits_command;
mod local_commands;
mod local_diff;
mod login;
mod login_secret_input;
mod markdown;
mod markdown_image;
mod mcp_actions;
mod mcp_argument_completion;
mod mcp_picker;
mod mcp_prompt;
mod mcp_resource;
mod media_attach;
mod message_history;
mod message_render;
mod model_actions;
mod model_performance;
mod model_picker;
mod mouse;
mod mouse_capture;
mod paste_burst;
mod pending_input;
#[cfg(test)]
mod performance_benchmarks;
mod permission_mode;
mod picker;
mod picker_input;
mod picker_overlay;
mod picker_overlay_layout;
mod picker_rows;
mod prompt_turn;
mod provider_actions;
mod provider_attempt;
mod provider_picker;
mod questionnaire;
mod questionnaire_input;
mod reasoning_metadata;
mod render;
mod rendered_entry;
mod run_lifecycle;
mod screen_layout;
mod scrollbar;
mod session_actions;
mod session_picker;
mod session_title;
mod sessions_hub;
mod setup_screen;
mod syntax;
pub(in crate::tui) mod terminal_graph;
mod transcript_events;
pub(crate) use session_title::SESSION_TITLE_PROMPT;
mod app_loop;
mod idle_input;
mod reasoning_phase;
mod rewind_actions;
mod skill_actions;
mod skill_picker;
// Always compiled: display_version() is used in release TUI chrome.
// Matrix/herdr injection paths stay no-ops outside debug builds.
mod smoke_injection;
mod status_overlay;
mod statusline;
mod stream;
mod stream_pace;
mod stream_preview;
mod subagent_attach;
mod subagent_panel;
mod terminal_events;
mod terminal_session;
mod text_selection;
mod theme;
mod theme_actions;
mod theme_picker;
mod theme_scheme;
mod theme_terminal;
mod tool_call_batch;
mod tool_card_render;
mod tool_diff;
mod tool_output_ui;
mod tool_search;
mod tree_actions;
mod turn_prompt;
mod usage_cost;
mod view;
mod view_composer;
mod view_scroll;
mod workflow_discover;
mod workflow_hub;
// Separate full-screen mode for an active workflow run. The chat hub hands off
// through terminal suspend when starting or resuming a run.
pub(crate) mod workflow;
mod workspace;

mod types;
use types::*;

use activity::{ActivityPhase, ActivityStatus, LoadingSpinner};
use app_state::{HistoryUi, InputUi, PendingWorkUi, TurnUi};
use approval::{approval_lines, ApprovalKeyOutcome};
use chat_media::{
    ChatMedia, ChatTextDocument, ComposerAttachment, MediaAttachId, PendingAttachmentSource,
};
use clipboard::ClipboardWriter;
use config_editor::{
    config_number_input_lines, resolve_web_search_editor_value, ConfigMutation, ConfigNumberInput,
    ConfigNumberKey, ConfigTextKey, ConfigToggle,
};
use copy_interaction::CodeBlockCopyTarget;
use event_adapter::{SdkEventAdapter, ViewEvent, ViewModelEvent};
use feed_image::FeedImage;
use frame_scheduler::FrameScheduler;
use goal::GoalState;
use inline_choice::{
    InlineChoice, InlineChoiceKeyOutcome, InlineChoiceModal, InlineChoiceOption,
    InlineChoicePending,
};
#[cfg(test)]
use inline_shell::InlineShellMode;
use login::PendingInteractiveLogin;
#[cfg(test)]
use login::SecretInput;
use paste_burst::PasteBurstEnter;
use picker::{
    sort_items_by_ascii_label, OverlayFocus, OverlayScrollbarDrag, PickerAction, PickerBadge,
    PickerBadgePlacement, PickerBadgeTone, PickerCursor, PickerItem, PickerKeyHints, PickerLayout,
    UiPicker,
};
use prompt_turn::FailedTurn;
#[cfg(test)]
use questionnaire::QuestionnaireComposer;
use questionnaire::{
    questionnaire_cursor_position, questionnaire_lines, questionnaire_notice_text,
    QuestionAnswerRequest, QuestionnaireReply, QuestionnaireResponseChannel,
};
use render::{
    char_prefix_display_width, display_width, input_cursor_position, input_lines,
    labeled_divider_line, picker_lines, session_header_lines, styled_line, tool_entry_lines,
    truncate_one_line, LineFill,
};
use scrollbar::HistoryScrollbar;
use session_title::PendingSessionTitle;
use statusline::{GoalStatus, StatusLine};
use subagent_attach::PendingSubagentAttach;
use subagent_panel::SubagentPanel;
use terminal_session::TerminalSession;
use text_selection::{highlight_selection, render_copy_notice, TextSelection};
use theme::Theme;
use turn_prompt::TurnPrompt;

#[cfg(test)]
use rho_providers::model::{ImageContent, ModelUsage};
use {
    crate::app::config_repository::ConfigRepository,
    crate::app::interactive_runtime::InteractiveRuntime,
    crate::commands::{self, CommandId, CommandInvocation},
    crate::herdr::{HerdrReporter, HerdrState},
    crate::keybindings::Keybindings,
    crate::permission::PermissionMode,
    crate::session::Session,
    rho_providers::credentials::CredentialStore,
    rho_providers::model::{
        catalog::{self, LoginTarget, ModelSelection},
        favorites,
        provider_models::refresh_provider_models_with_store,
        ContentBlock, Message, ModelMetadata, ReasoningRequestSource, UnavailableProvider,
    },
    rho_providers::provider,
    rho_providers::reasoning::ReasoningLevel,
};
/// Viewport height used by line-level tests that render without a real terminal.
#[cfg(test)]
const DEFAULT_TUI_HEIGHT: u16 = 18;
const MAX_COMMAND_SUGGESTIONS: usize = 5;
const MIN_COMMAND_DESCRIPTION_WIDTH: usize = 7;
const RECOVERED_HISTORY_LINE_LIMIT: usize = 200;
/// Shared cadence for releasing held stream text and refreshing partial previews.
const STREAM_UI_TICK: Duration = Duration::from_millis(24);
const STREAM_PREVIEW_MIN_CHARS: usize = 2;
const HISTORY_SCROLLBAR_REVEAL_DURATION: Duration = Duration::from_millis(1200);
const HISTORY_MOUSE_SCROLL_LINES: usize = 3;
pub struct TuiBootstrap {
    pub runtime: RuntimeModelView,
    pub session: SessionBootstrap,
    pub services: ApplicationServices,
}

pub struct RuntimeModelView {
    pub cwd: PathBuf,
    pub provider: String,
    pub model: String,
    pub(crate) model_aliases: crate::model_aliases::ModelAliases,
    pub reasoning: ReasoningLevel,
    pub service_tier: Option<rho_sdk::model::ServiceTier>,
    pub reasoning_source: ReasoningRequestSource,
    pub permission_mode: PermissionMode,
    pub show_reasoning_output: bool,
    pub zen_mode: bool,
    /// Offer the advisor tool, backed by the `advisor` internal agent's model.
    pub advisor_mode: bool,
    pub auth: String,
    pub internal_agents:
        std::collections::BTreeMap<String, crate::config::InternalAgentModelConfig>,
    pub favorite_models: Vec<String>,
    pub max_tool_output_lines: usize,
    pub keybindings: Keybindings,
    pub prompt_templates: crate::prompt_templates::PromptTemplates,
}

/// How reasoning appears in the transcript for the current display settings.
///
/// Zen and `show_reasoning_output` collapse into one exclusive policy so call
/// sites never invert complementary booleans.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReasoningChrome {
    /// Stream and store reasoning text in the transcript.
    FullText,
    /// Suppress reasoning text; show live `Thinking...` while the stretch is open.
    ThinkingPlaceholder,
    /// Suppress reasoning text and `Thinking...` (zen mode).
    Hidden,
}

impl RuntimeModelView {
    fn model_call_profile(&self) -> rho_sdk::ModelCallProfile {
        rho_sdk::ModelCallProfile {
            provider: self.provider.clone(),
            model: self.model.clone(),
            reasoning: self.reasoning,
            service_tier: self.service_tier,
        }
    }

    /// Exclusive reasoning display policy for the current session settings.
    pub(crate) fn reasoning_chrome(&self) -> ReasoningChrome {
        if self.zen_mode {
            ReasoningChrome::Hidden
        } else if self.show_reasoning_output {
            ReasoningChrome::FullText
        } else {
            ReasoningChrome::ThinkingPlaceholder
        }
    }

    /// Whether the TUI should render reasoning text for this session.
    pub(crate) fn displays_reasoning_output(&self) -> bool {
        matches!(self.reasoning_chrome(), ReasoningChrome::FullText)
    }

    /// Whether tool cards and reasoning blocks are visible in the transcript.
    ///
    /// Zen mode suppresses that work chrome while keeping the live activity rail
    /// and subagent rows so the session still shows progress. Reasoning text vs
    /// `Thinking...` vs neither is [`Self::reasoning_chrome`].
    pub(crate) fn shows_work_chrome(&self) -> bool {
        !self.zen_mode
    }

    pub(crate) fn history_render_settings(
        &self,
        width: usize,
        max_image_height: u16,
    ) -> history_cache::HistoryRenderSettings {
        history_cache::HistoryRenderSettings {
            width,
            max_tool_output_lines: self.max_tool_output_lines,
            zen_mode: self.zen_mode,
            theme_generation: theme::Theme::generation(),
            max_image_height,
        }
    }

    fn fast_mode_active(&self) -> bool {
        self.service_tier == Some(rho_sdk::model::ServiceTier::Priority)
            && rho_providers::providers::openai::supports_fast_mode(&self.provider, &self.model)
    }
}

pub struct SessionBootstrap {
    pub session_id: Option<String>,
    pub recovered_messages: Vec<Message>,
    pub open_resume_picker: bool,
}

pub struct ApplicationServices {
    pub(crate) config_repository: ConfigRepository,
    /// Set when this launch should open the first-run setup screen, and at
    /// which step. `None` for a returning session.
    pub(crate) first_run: Option<first_run::SetupEntry>,
    pub auth_unavailable: Option<String>,
    pub update_notice: Option<String>,
    pub pending_update_notice: Option<tokio::task::JoinHandle<Option<String>>>,
    pub diagnostics: crate::diagnostics::RuntimeDiagnostics,
    pub herdr: HerdrReporter,
}
pub struct TuiResult {
    pub resume_session_id: Option<String>,
    exit_summary: Option<String>,
}
pub(crate) use attachment::{
    run as run_attachment, translate_run_event, AttachmentDisplaySettings,
};

pub async fn run(agent: &mut InteractiveRuntime, info: TuiBootstrap) -> anyhow::Result<TuiResult> {
    let mut terminal = ratatui::init();
    Theme::initialize_from_terminal();
    let startup_theme = info
        .services
        .config_repository
        .load()
        .map(|config| config.theme)
        .unwrap_or_else(|_| "terminal".into());
    Theme::apply_committed(&startup_theme);
    let herdr = info.services.herdr.clone();
    let herdr_graphics = herdr.graphics_capability().await;
    let initial_state = if info.services.auth_unavailable.is_some() {
        HerdrState::Blocked
    } else {
        HerdrState::Idle
    };
    herdr
        .report_state(
            initial_state,
            info.services.auth_unavailable.as_deref(),
            info.session.session_id.as_deref(),
        )
        .await;
    let result = {
        let injected = smoke_injection::after_terminal_init();

        match injected {
            Ok(()) => {
                let mut app = App::new(
                    info,
                    herdr_graphics,
                    agent.mcp_report().clone(),
                    agent.mcp_catalog().clone(),
                    agent.plugins_report().clone(),
                );
                app.terminal_session = Some(TerminalSession::acquire());
                if let Some(manager) = agent.subagents() {
                    app.subagent_inbox.bind(manager);
                }
                let result = app.run(&mut terminal, agent).await;
                if let Some(manager) = agent.subagents() {
                    manager.unbind_host_input();
                    manager.unbind_notices();
                }
                result
            }
            Err(error) => Err(error),
        }
    };
    herdr.release().await;
    ratatui::restore();
    if let Ok(result) = &result {
        app_loop::print_exit_summary(result.exit_summary.as_deref())?;
    }
    result
}

struct App {
    info: TuiBootstrap,
    terminal_session: Option<TerminalSession>,
    statusline: StatusLine,
    subagent_panel: SubagentPanel,
    subagent_inbox: subagent_inbox::SubagentInbox,
    pending_subagent_questionnaire: Option<PendingSubagentQuestionnaire>,
    input_ui: InputUi,
    /// Tiny disappearing feedback toast. Write only through [`App::set_status`]
    /// / [`App::notify_status`].
    status_overlay: Option<status_overlay::StatusOverlay>,
    /// Last status text for callers that inspect mode feedback.
    last_status: String,
    should_quit: bool,
    ctrl_c_streak: u8,
    streams: StreamUi,
    turn: TurnUi,
    image_picker: Option<ratatui_image::picker::Picker>,
    pending: PendingWorkUi,
    pending_inline_shells: Vec<inline_shell::PendingShellTask>,
    deferred_inline_shell_context: Vec<inline_shell::DeferredShellContext>,
    goal: Option<GoalState>,
    history: HistoryUi,
    credential_store: Arc<dyn CredentialStore>,
    available_auths: Vec<String>,
    using_unavailable_provider: bool,
    pending_interactive_login: Option<PendingInteractiveLogin>,
    /// Active step of the first-launch setup screen, or `None` for a normal
    /// session. While set, the screen replaces all session chrome.
    setup_screen: Option<setup_screen::SetupStep>,
    pending_usage_limits: Option<tokio::task::JoinHandle<limits_command::LimitsFetchResult>>,
    pending_changelog: Option<tokio::task::JoinHandle<changelog_command::ChangelogFetchResult>>,
    usage_limits_client: reqwest::Client,
    usage: UsageUi,
    model_metadata: Option<ModelMetadata>,
    pending_model_metadata: Option<tokio::task::JoinHandle<Option<ModelMetadata>>>,
    pending_model_metadata_reasoning: Option<(ReasoningLevel, ReasoningRequestSource)>,
    pending_update_notice: Option<tokio::task::JoinHandle<Option<String>>>,
    pending_model_selection: Option<InteractiveModelSelection>,
    internal_agent_model_target: Option<agent_picker::InternalAgentModelTarget>,
    /// Set when the user dismisses the startup Auto classifier picker. The next
    /// idle reconcile demotes Auto → Supervised so cancel stays sync and never
    /// needs an optional runtime handle on shared picker Esc paths.
    pending_auto_classifier_demote: bool,
    agent_editor_session: Option<agent_editor::AgentEditSession>,
    sessions_hub_state: sessions_hub::SessionsHubState,
    pending_session_title: Option<PendingSessionTitle>,
    /// Set by `/title` so auto-title generation cannot overwrite a manual name.
    session_title_locked: bool,
    clipboard: Box<dyn ClipboardWriter + Send>,
    media_attach_tasks: Vec<media_attach::MediaAttachTask>,
    /// Last known terminal height for discrete feed-image row budgets.
    terminal_height: usize,
    /// Shared composer attachment layout for the current frame/width.
    composer_attachment_layout_cache: Option<composer_attachments::ComposerAttachmentLayoutCache>,
    pending_subagent_attaches: Vec<PendingSubagentAttach>,
    last_mouse_position: Option<(u16, u16)>,
    /// Screen-space drag selection for text outside the history area.
    screen_selection: Option<TextSelection>,
    /// MCP inventory for `/mcp` and `/doctor` (session snapshot from tool assembly).
    mcp_report: crate::tools::mcp::McpSessionReport,
    /// Prompts and resources connected MCP servers offer, for palette matching.
    mcp_catalog: crate::tools::mcp::McpCatalog,
    /// Fetched argument suggestions for the MCP prompt being typed, so palette
    /// matching reads a local cache instead of awaiting a server.
    mcp_argument_completions: mcp_argument_completion::McpArgumentCompletions,
    /// Agent Plugins load report captured at session start for `/doctor`.
    plugins_report: crate::plugins::PluginLoadReport,
}

struct PendingSubagentQuestionnaire {
    run_id: String,
    agent_id: String,
    reply_rx: oneshot::Receiver<QuestionnaireReply>,
    response_tx: tokio::sync::oneshot::Sender<Result<rho_sdk::HostInputResponse, rho_sdk::Error>>,
}

#[cfg(test)]
#[path = "tui/app_tests.rs"]
mod tests;