rho-coding-agent 1.40.1

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
//! Core TUI value types shared across interactive modules.

use std::time::{Duration, Instant};

use super::{
    approval::ApprovalComposer,
    commands::{self, CommandSpec},
    config_editor::ConfigNumberInput,
    feed_image::FeedImage,
    info_command,
    inline_choice::InlineChoiceModal,
    inline_shell::InlineShellMode,
    limits_command,
    login::SecretInput,
    markdown::CodeFenceState,
    picker::UiPicker,
    prompt_turn::FailedTurn,
    questionnaire::QuestionnaireComposer,
    stream::AppendOnlyStream,
    stream_pace::StreamPacer,
    theme::Theme,
    usage_cost::{AttemptAwareRunUsage, UsageCostTracker},
};
use ratatui::{
    style::{Modifier, Style},
    text::Line,
};
use rho_providers::model::{
    catalog::{LoginTarget, ModelSelection},
    ContextUsage, ModelUsage,
};

#[cfg(test)]
pub(super) struct ActiveFrame {
    pub(in crate::tui) lines: Vec<Line<'static>>,
}

pub(super) struct LiveStreamPreview {
    pub(in crate::tui) kind: StreamKind,
    pub(in crate::tui) text: String,
    pub(in crate::tui) include_leading_blank: bool,
}

pub(super) struct SessionHeaderCache {
    pub(in crate::tui) width: usize,
    pub(in crate::tui) update_notice: Option<String>,
    pub(in crate::tui) setup: super::first_run::SetupState,
    /// Rebuild styled header lines when the active theme changes.
    pub(in crate::tui) theme_generation: u64,
    pub(in crate::tui) lines: Vec<Line<'static>>,
}

#[derive(Debug, PartialEq, Eq)]
pub(super) struct InteractiveModelSelection {
    pub(in crate::tui) selection: ModelSelection,
    pub(in crate::tui) alias: Option<String>,
}

/// Live assistant/reasoning stream UI state owned by [`super::App`].
#[derive(Default)]
pub(super) struct StreamUi {
    pub(in crate::tui) assistant_stream: AppendOnlyStream,
    pub(in crate::tui) assistant_stream_code_fence: CodeFenceState,
    pub(in crate::tui) reasoning_stream: AppendOnlyStream,
    pub(in crate::tui) reasoning_stream_code_fence: CodeFenceState,
    pub(in crate::tui) current_stream_kind: Option<StreamKind>,
    /// Next opportunity to release held text and refresh the partial preview.
    pub(in crate::tui) stream_tick_deadline: Option<Instant>,
    pub(in crate::tui) live_stream_preview: Option<LiveStreamPreview>,
    /// Provider text waiting to be released into the active stream.
    pub(in crate::tui) hold: String,
    pub(in crate::tui) pacer: StreamPacer,
}

impl StreamUi {
    pub(super) fn reset(&mut self) {
        self.assistant_stream.reset();
        self.assistant_stream_code_fence = CodeFenceState::default();
        self.reasoning_stream.reset();
        self.reasoning_stream_code_fence = CodeFenceState::default();
        self.current_stream_kind = None;
        self.stream_tick_deadline = None;
        self.live_stream_preview = None;
        self.hold.clear();
        self.pacer.reset();
    }

    pub(super) fn loading_streams_active(&self) -> bool {
        !self.hold.is_empty()
            || !self.assistant_stream.is_empty()
            || !self.reasoning_stream.is_empty()
    }
}

/// Cumulative and in-flight usage snapshots shown by the TUI.
#[derive(Default)]
pub(super) struct UsageUi {
    pub(in crate::tui) cumulative_usage: Option<ModelUsage>,
    pub(in crate::tui) usage_cost_tracker: UsageCostTracker,
    // SDK usage updates are cumulative within a run. These snapshots let the TUI
    // replace active usage while preserving totals from prior runs and steps.
    pub(in crate::tui) usage_before_current_run: Option<ModelUsage>,
    pub(in crate::tui) run_usage: AttemptAwareRunUsage,
    pub(in crate::tui) latest_usage: Option<ModelUsage>,
    pub(in crate::tui) model_performance: super::model_performance::ModelPerformanceTracker,
    pub(in crate::tui) current_context: Option<ContextUsage>,
    /// In-flight stream estimate while the provider has not reported usage yet.
    pub(in crate::tui) live_stream: super::usage_cost::LiveStreamUsageEstimate,
    // Cumulative cost from completed subagents (bg + fg), claimed once per run via
    // SubagentManager::claim_terminal_costs_usd_micros during panel refresh.
    pub(in crate::tui) subagent_total_cost_usd_micros: u64,
    // Cumulative cost from finished advisor calls, claimed via
    // AdvisorSessionStore::claim_cost_usd_micros during the same poll path.
    pub(in crate::tui) advisor_total_cost_usd_micros: u64,
}

impl UsageUi {
    /// Non-main session cost folded into the statusline total.
    pub(in crate::tui) fn extra_cost_usd_micros(&self) -> u64 {
        self.subagent_total_cost_usd_micros
            .saturating_add(self.advisor_total_cost_usd_micros)
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum InputSubmissionMode {
    #[default]
    ParseCommands,
    Prompt,
}

#[derive(Debug, Default)]
pub(super) enum ComposerMode {
    #[default]
    Input,
    Picker(UiPicker),
    SecretInput(SecretInput),
    ConfigNumberInput(ConfigNumberInput),
    TextInput(super::text_input::TextInput),
    InteractivePending(LoginTarget),
    InlineChoice(InlineChoiceModal),
    Questionnaire(QuestionnaireComposer),
    Approval(ApprovalComposer),
}

impl ComposerMode {
    pub(super) fn blocks_auto_continue(&self) -> bool {
        match self {
            Self::InlineChoice(modal) => modal.blocks_auto_continue(),
            _ => false,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct PasteSegment {
    pub(in crate::tui) start: usize,
    pub(in crate::tui) marker_len: usize,
    pub(in crate::tui) content: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct QueuedPrompt {
    pub(in crate::tui) prompt: String,
    pub(in crate::tui) display_prompt: String,
    pub(in crate::tui) paste_segments: Vec<PasteSegment>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct InputDraft {
    pub(in crate::tui) input: String,
    pub(in crate::tui) paste_segments: Vec<PasteSegment>,
    pub(in crate::tui) submission_mode: InputSubmissionMode,
    pub(in crate::tui) shell_mode: Option<InlineShellMode>,
}

#[derive(Clone, Debug)]
pub(super) struct FileMatchCache {
    pub(in crate::tui) query: String,
    pub(in crate::tui) matches: super::file_picker::FilePaletteMatches,
    pub(in crate::tui) refreshed_at: Instant,
}

/// Discovered skills reused across command palette queries, so typing a slash
/// command does not re-walk skill directories on every keystroke.
pub(super) struct SkillMatchCache {
    pub(in crate::tui) skills: std::sync::Arc<Vec<crate::skills::Skill>>,
    pub(in crate::tui) refreshed_at: Instant,
}

impl From<&str> for QueuedPrompt {
    fn from(prompt: &str) -> Self {
        Self {
            prompt: prompt.to_string(),
            display_prompt: prompt.to_string(),
            paste_segments: Vec::new(),
        }
    }
}

impl PasteSegment {
    pub(super) fn end(&self) -> usize {
        self.start + self.marker_len
    }
}

#[derive(Debug)]
pub(super) struct SessionTitleResult {
    pub(in crate::tui) session_id: String,
    pub(in crate::tui) title: anyhow::Result<String>,
}

#[derive(Clone, Debug)]
pub(super) struct CommandChoice {
    pub(in crate::tui) name: String,
    pub(in crate::tui) usage: String,
    pub(in crate::tui) description: String,
    pub(in crate::tui) kind: CommandChoiceKind,
}

#[derive(Debug, PartialEq)]
pub(super) enum TurnOutcome {
    Completed,
    Interrupted,
    /// User cancelled interactive work such as a questionnaire.
    Cancelled,
    Failed(Box<FailedTurn>),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum TurnOutcomeKind {
    Completed,
    Interrupted,
    Cancelled,
    Failed,
}

impl TurnOutcome {
    pub(super) fn kind(&self) -> TurnOutcomeKind {
        match self {
            Self::Completed => TurnOutcomeKind::Completed,
            Self::Interrupted => TurnOutcomeKind::Interrupted,
            Self::Cancelled => TurnOutcomeKind::Cancelled,
            Self::Failed(_) => TurnOutcomeKind::Failed,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum HistoryScroll {
    #[default]
    Bottom,
    Manual {
        top_line: usize,
    },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum CommandChoiceKind {
    Builtin(&'static CommandSpec),
    BuiltinArgument(&'static commands::CommandArgumentChoice),
    PromptTemplate(String),
    Skill,
    /// A prompt offered by a connected MCP server. Expanded on submit, because
    /// `prompts/get` is a round-trip the palette cannot make.
    McpPrompt,
    /// One value a server suggested for the prompt argument under the cursor.
    /// Carries the char range it fills so picking it settles that argument
    /// alone, leaving the command and any other arguments as typed.
    McpPromptArgument {
        value: std::ops::Range<usize>,
    },
}

/// Clock for the live elapsed decoration: preserved across card replacement,
/// started when a card is first seen running, absent otherwise.
pub(super) fn live_started_at(
    previous: Option<&ToolEntry>,
    status: rho_tools::tool_card::ToolStatus,
) -> Option<Instant> {
    previous
        .and_then(|entry| entry.started_at)
        .or_else(|| matches!(status, rho_tools::tool_card::ToolStatus::Running).then(Instant::now))
}

#[derive(Clone, Debug)]
pub(super) struct ToolEntry {
    /// Structured Call + Children card. Sole render input for tool rows.
    pub(in crate::tui) card: rho_tools::tool_card::ToolCard,
    pub(in crate::tui) expanded: bool,
    pub(in crate::tui) image: Option<FeedImage>,
    /// Wall clock for live shell elapsed (`timeout … · 1.2s`) while a shell
    /// call runs. Set when a tool starts running; preserved across card
    /// updates; absent on historical, finished, interrupted, and preview rows.
    pub(in crate::tui) started_at: Option<Instant>,
}

#[derive(Clone, Debug)]
pub(super) enum Entry {
    User(String),
    Assistant(String),
    Reasoning(ReasoningEntry),
    Tool(ToolEntry),
    Notice(String),
    RuntimeInfo(Box<info_command::RuntimeInfo>),
    Changelog(Box<crate::changelog::ChangelogDisplay>),
    UsageLimits(limits_command::LimitsDisplay),
    Error(String),
}

/// Streamed reasoning text plus optional post-phase thought duration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ReasoningEntry {
    pub(in crate::tui) text: String,
    pub(in crate::tui) thought_for: Option<Duration>,
}

impl ReasoningEntry {
    pub(super) fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            thought_for: None,
        }
    }

    pub(super) fn summary_only(thought_for: Duration) -> Self {
        Self {
            text: String::new(),
            thought_for: Some(thought_for),
        }
    }
}

impl From<&str> for ReasoningEntry {
    fn from(text: &str) -> Self {
        Self::new(text)
    }
}

impl From<String> for ReasoningEntry {
    fn from(text: String) -> Self {
        Self::new(text)
    }
}

impl Entry {
    pub(super) fn is_provider_replaceable(&self) -> bool {
        matches!(self, Self::Assistant(_) | Self::Reasoning(_))
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum StreamKind {
    Assistant,
    Reasoning,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PasteBurstKey {
    Char(char),
    Enter,
}

#[derive(Debug, PartialEq, Eq)]
pub(super) enum FinalAnswerDelta<'a> {
    None,
    Append(&'a str),
    Mismatch,
}

impl StreamKind {
    pub(super) fn style(self) -> Style {
        match self {
            Self::Assistant => Theme::text(),
            Self::Reasoning => Theme::dim().add_modifier(Modifier::DIM),
        }
    }

    pub(super) fn entry(self, text: String) -> Entry {
        match self {
            Self::Assistant => Entry::Assistant(text),
            Self::Reasoning => Entry::Reasoning(ReasoningEntry::new(text)),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum StreamControl {
    Continue,
    Interrupt,
    Resize,
    ApprovalResolved,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum HerdrUserWait {
    Approval,
    Questionnaire,
}

impl HerdrUserWait {
    pub(super) const fn message(self) -> &'static str {
        match self {
            Self::Approval => "waiting for approval",
            Self::Questionnaire => "waiting for your answers",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum RunningInputMode {
    Turn,
    Compacting,
}

#[derive(Clone, Copy, Debug)]
pub(super) enum HistoryDirection {
    Previous,
    Next,
}