rho-coding-agent 1.48.0

A lightweight agent harness inspired by Pi
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
//! The `advisor` tool: a reviewer model reads the session and advises the executor.
//!
//! The tool takes no arguments. Rho serializes the session itself, so nothing
//! the executor writes reaches the advisor. The advisor runs as a one-shot Rho
//! agent with no tools and returns only advice text. While the request is in
//! flight, live phase and text snapshots stream into the tool card.

mod transcript;

use std::{
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

use rho_sdk::{
    model::{ModelUsage, ToolSpec},
    tool::{
        OperationKind, Tool as SdkTool, ToolContext, ToolError, ToolErrorKind, ToolFuture,
        ToolInvocation, ToolMetadata, ToolOutput, ToolProgress, ToolProgressSender, ToolSecurity,
    },
    CancellationToken, Session, SessionId,
};
use serde_json::json;
use tokio::sync::watch;

use crate::{
    agent::{
        effective_internal_agent_reasoning, internal_agent_requires_model, internal_definition,
        run_one_shot_with_provider, OneShotAgentRequest, OneShotPhase, OneShotUpdate,
        ADVISOR_AGENT_ID,
    },
    config::{Config, InternalAgentModelConfig, InternalAgentTarget},
    credential_store::build_provider,
};

pub(crate) use transcript::{TranscriptBudget, DEFAULT_TRANSCRIPT_BUDGET};

pub(crate) const TOOL_NAME: &str = "advisor";

const USAGE_PURPOSE: &str = "advisor";

const TOOL_DESCRIPTION: &str = "Consult a stronger reviewer model about this session. Takes NO parameters: your whole conversation history, including the task, every tool call you made, and every result you saw, is forwarded automatically. Returns strategic guidance on what to do next.\n\nDo not call advisor as your first action. Explore first - read the relevant files, reproduce the issue, understand the shape of the task - then consult before committing to an approach.\n\nAlso call advisor:\n- When stuck: errors recurring, approach not converging, results that do not fit.\n- When considering a change of approach.\n- When you believe the task is complete. BEFORE this call, make your deliverable durable: write the file, save the result, commit the change.\n\nOn short reactive tasks where the next action follows from tool output you just read, skip advisor. Do not call it just because it exists.\n\nGive the advice serious weight. If you follow a step and it fails in practice, or you have primary-source evidence that contradicts a specific claim, adapt. If you have already retrieved data pointing one way and the advisor points another, do not switch silently: surface the conflict in one more advisor call.";

const NO_MODEL_MESSAGE: &str =
    "advisor mode has no advisor model. Choose one with /advisor, then call advisor again.";

const NO_SESSION_MESSAGE: &str = "the advisor is not attached to a live session";

const NO_WORKSPACE_MESSAGE: &str = "the advisor requires a configured workspace";

const NO_GUIDANCE_MESSAGE: &str = "the advisor model returned no guidance";

/// The advisor's configured model, or `None` when the user has not chosen one.
///
/// The advisor is the one internal agent with no conversation-model fallback
/// (see [`internal_agent_requires_model`]): an advisor that mirrors the
/// executor adds nothing, so an unset model stays unset.
pub(crate) fn advisor_model(config: &Config) -> Option<&InternalAgentModelConfig> {
    debug_assert!(internal_agent_requires_model(ADVISOR_AGENT_ID));
    config.internal_agent_model(ADVISOR_AGENT_ID)
}

/// Reasoning level the advisor run will use.
///
/// Explicit config wins. Otherwise the reserved advisor definition default
/// applies (medium), normalized to the selection's model capabilities.
pub(crate) fn advisor_effective_reasoning(
    model: &InternalAgentModelConfig,
) -> rho_providers::reasoning::ReasoningLevel {
    effective_internal_agent_reasoning(ADVISOR_AGENT_ID, model)
}

/// Whether the `advisor` tool can run under this configuration.
///
/// Advisor mode on with no advisor model is a real state; the tool stays off
/// until the user picks a model.
pub(crate) fn advisor_available(config: &Config) -> bool {
    config.advisor_mode && advisor_model(config).is_some()
}

/// Builds the `advisor` tool.
///
/// It owns no resources beyond the store and needs no shutdown, so the tool set
/// registers it directly instead of through a bundle. That also lets advisor
/// mode register and remove it mid-session without rebuilding the tool set.
pub(super) fn advisor_tool(store: AdvisorSessionStore) -> Arc<dyn SdkTool> {
    Arc::new(AdvisorTool::new(store, DEFAULT_TRANSCRIPT_BUDGET))
}

/// Live session state the `advisor` tool reads when the executor calls it.
///
/// Built with the tool set, before a session exists, then bound afterwards the
/// way `WebAccessStore` and `SubagentManager` are. Holds a [`Session`] handle
/// rather than a copy of the history, so a replaced session rebinds in one
/// place and the tool always reads current state.
#[derive(Clone, Default)]
pub struct AdvisorSessionStore {
    state: Arc<Mutex<AdvisorSessionState>>,
}

#[derive(Default)]
struct AdvisorSessionState {
    session: Option<Session>,
    system_prompt: Option<String>,
    model: Option<InternalAgentModelConfig>,
    /// Provider-reported advisor spend not yet folded into the parent TUI total.
    unclaimed_cost_usd_micros: u64,
}

impl AdvisorSessionStore {
    pub fn new() -> Self {
        Self::default()
    }

    /// Points the advisor at the session the executor is running.
    ///
    /// Changing the session id drops unclaimed advisor spend so a new
    /// conversation never inherits cost from the previous one. Same-id rebinds
    /// (runtime policy rebuilds) keep the accumulator.
    pub fn bind_session(&self, session: Session) {
        let mut state = self.lock();
        let same_session = state
            .session
            .as_ref()
            .is_some_and(|current| current.id() == session.id());
        if !same_session {
            state.unclaimed_cost_usd_micros = 0;
        }
        state.session = Some(session);
    }

    /// Records the executor system prompt, which the advisor reviews alongside
    /// the messages.
    pub fn bind_system_prompt(&self, prompt: Option<String>) {
        self.lock().system_prompt = prompt;
    }

    /// Replaces the advisor model, so a `/advisor` model change applies to the
    /// next call without rebuilding the tool set.
    pub fn set_model(&self, model: Option<InternalAgentModelConfig>) {
        self.lock().model = model;
    }

    /// Currently configured advisor model, if any.
    pub fn model(&self) -> Option<InternalAgentModelConfig> {
        self.lock().model.clone()
    }

    /// Fold provider-reported cost from a finished advisor call into the
    /// unclaimed total.
    ///
    /// Only `cost_usd_micros` counts — same contract as subagent terminal
    /// costs. Tokens-only providers and models without a provider cost stay
    /// silent; the TUI does not estimate advisor spend from metadata.
    pub fn note_usage(&self, usage: &ModelUsage) {
        let Some(cost) = usage.cost_usd_micros.filter(|cost| *cost > 0) else {
            return;
        };
        let mut state = self.lock();
        state.unclaimed_cost_usd_micros = state.unclaimed_cost_usd_micros.saturating_add(cost);
    }

    /// Takes advisor costs that have not yet been added to the parent session
    /// total. Safe to call from any TUI poll path; returns 0 when nothing is
    /// new. Costs claimed only through this poll can be lost if the TUI exits
    /// before the next refresh - same as subagent terminal-cost claims.
    pub fn claim_cost_usd_micros(&self) -> u64 {
        let mut state = self.lock();
        let claimed = state.unclaimed_cost_usd_micros;
        state.unclaimed_cost_usd_micros = 0;
        claimed
    }

    #[cfg(test)]
    fn unclaimed_cost_usd_micros(&self) -> u64 {
        self.lock().unclaimed_cost_usd_micros
    }

    #[cfg(test)]
    pub fn system_prompt(&self) -> Option<String> {
        self.lock().system_prompt.clone()
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, AdvisorSessionState> {
        self.state
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn request(&self, budget: TranscriptBudget) -> Result<AdvisorRequest, ToolError> {
        let state = self.lock();
        let model = state
            .model
            .clone()
            .ok_or_else(|| execution_error(NO_MODEL_MESSAGE))?;
        let session = state
            .session
            .as_ref()
            .ok_or_else(|| execution_error(NO_SESSION_MESSAGE))?;
        // Live history, not committed history: the advisor is called from
        // inside the turn it must review.
        let messages = session.live_history();
        Ok(AdvisorRequest {
            model,
            session_id: session.id().clone(),
            transcript: transcript::render_transcript(
                state.system_prompt.as_deref(),
                &messages,
                budget,
            ),
        })
    }
}

#[derive(Debug)]
struct AdvisorRequest {
    model: InternalAgentModelConfig,
    session_id: SessionId,
    transcript: String,
}

pub(crate) struct AdvisorTool {
    store: AdvisorSessionStore,
    budget: TranscriptBudget,
}

impl AdvisorTool {
    pub(crate) fn new(store: AdvisorSessionStore, budget: TranscriptBudget) -> Self {
        Self { store, budget }
    }
}

impl SdkTool for AdvisorTool {
    fn spec(&self) -> ToolSpec {
        // Deliberately model-agnostic. A `/advisor` model change lands on the
        // store without rebuilding the tool set, so naming the reviewer here
        // would rewrite what the executor was already told, or go stale. The
        // reviewer is named in the system prompt and in switch notices instead.
        ToolSpec {
            name: TOOL_NAME.into(),
            description: TOOL_DESCRIPTION.into(),
            input_schema: json!({
                "type": "object",
                "additionalProperties": false,
                "properties": {}
            }),
        }
    }

    fn security(&self) -> ToolSecurity {
        ToolSecurity::built_in([])
    }

    // The advisor reviews the turn it was called from, which only the
    // published in-flight history contains.
    fn reads_live_history(&self) -> bool {
        true
    }

    fn call<'a>(&'a self, _invocation: ToolInvocation, context: ToolContext) -> ToolFuture<'a> {
        Box::pin(async move {
            let workspace_path = context
                .workspace_root()
                .map(std::path::Path::to_path_buf)
                .ok_or_else(|| execution_error(NO_WORKSPACE_MESSAGE))?;
            let request = self.store.request(self.budget)?;
            let (advice, usage) = consult_advisor(
                request,
                workspace_path,
                context.cancellation().clone(),
                context.progress().clone(),
            )
            .await?;
            // Note before the empty-guidance check: the provider already spent.
            self.store.note_usage(&usage);
            if advice.is_empty() {
                return Err(execution_error(NO_GUIDANCE_MESSAGE));
            }
            Ok(ToolOutput::text(advice)
                .metadata(ToolMetadata::new().operation(OperationKind::Read)))
        })
    }
}

/// Runs the advisor and returns its guidance plus provider usage.
///
/// Every failure comes back as a tool error, never as a run failure, so a
/// broken advisor leaves the executor's turn intact. Successful provider runs
/// (including empty text) return usage so the caller can fold cost into the
/// parent session total. Live updates stream into `progress` as plain guidance
/// text plus a phase in metadata; the final tool output stays plain guidance.
async fn consult_advisor(
    request: AdvisorRequest,
    workspace_path: PathBuf,
    cancellation: CancellationToken,
    progress: ToolProgressSender,
) -> Result<(String, ModelUsage), ToolError> {
    let AdvisorRequest {
        model,
        session_id,
        transcript,
    } = request;
    let reasoning = advisor_effective_reasoning(&model);
    match &model.target {
        InternalAgentTarget::Rho(selection) => {
            let reference = model.display_reference();
            let provider = build_provider(
                &selection.provider,
                &selection.model,
                reasoning,
                &selection.auth,
            )
            .await
            .map_err(|error| {
                execution_error(format!(
                    "advisor model {reference} could not start: {error}. Choose another advisor model with /advisor."
                ))
            })?;
            consult_advisor_with_provider(
                provider.as_ref(),
                &session_id,
                &workspace_path,
                transcript,
                reasoning,
                cancellation,
                progress,
            )
            .await
        }
        InternalAgentTarget::ClaudeCli { model } => {
            consult_advisor_with_claude_cli(
                model.clone(),
                reasoning,
                &workspace_path,
                transcript,
                cancellation,
                progress,
            )
            .await
        }
    }
}

/// Runs the advisor on the Claude Code CLI.
///
/// Same contract as the Rho path: one turn, no tools, guidance text back. The
/// call bills to the user's Claude subscription, so the cost Claude reports
/// folds into the parent total exactly as a provider's does.
async fn consult_advisor_with_claude_cli(
    model: Option<String>,
    reasoning: rho_providers::reasoning::ReasoningLevel,
    workspace_path: &Path,
    transcript: String,
    cancellation: CancellationToken,
    progress: ToolProgressSender,
) -> Result<(String, ModelUsage), ToolError> {
    let (updates_tx, updates_rx) =
        watch::channel(OneShotUpdate::new(OneShotPhase::WaitingForProvider, ""));
    let started = crate::claude_runtime::one_shot::run_one_shot(
        crate::claude_runtime::one_shot::ClaudeOneShotRequest {
            system_prompt: crate::agent::ADVISOR_PROMPT,
            input: transcript,
            model,
            reasoning: Some(reasoning),
            cwd: workspace_path.to_path_buf(),
            cancellation,
        },
        Some(updates_tx),
    );
    let forward_progress = forward_advisor_progress(updates_rx, progress);
    let (result, ()) = tokio::join!(started, forward_progress);
    let result = result.map_err(|error| {
        if error == crate::claude_runtime::one_shot::CANCELLATION_ERROR {
            execution_error("the advisor request was cancelled")
        } else {
            execution_error(format!("the advisor request failed: {error}"))
        }
    })?;
    Ok((result.text, result.usage))
}

async fn consult_advisor_with_provider(
    provider: &dyn rho_sdk::provider::ModelProvider,
    session_id: &SessionId,
    workspace_path: &Path,
    transcript: String,
    reasoning: rho_providers::reasoning::ReasoningLevel,
    cancellation: CancellationToken,
    progress: ToolProgressSender,
) -> Result<(String, ModelUsage), ToolError> {
    let usage_recording = crate::usage::default_recording().await;
    let (updates_tx, updates_rx) =
        watch::channel(OneShotUpdate::new(OneShotPhase::WaitingForProvider, ""));
    let started = run_one_shot_with_provider(
        provider,
        OneShotAgentRequest {
            definition: internal_definition(ADVISOR_AGENT_ID),
            usage_purpose: USAGE_PURPOSE,
            reasoning: Some(reasoning),
            input: vec![rho_sdk::model::ContentBlock::Text(transcript)],
            cancellation,
            session_id,
            workspace_path,
        },
        usage_recording,
        Some(updates_tx),
    );
    let forward_progress = forward_advisor_progress(updates_rx, progress);
    let (result, ()) = tokio::join!(started, forward_progress);
    let result =
        result.map_err(|error| execution_error(format!("the advisor request failed: {error}")))?;
    let advice = result.texts.join("\n").trim().to_owned();
    Ok((advice, result.usage))
}

/// Forwards latest-wins one-shot snapshots into tool progress.
///
/// Guidance stays in the progress message. Phase rides in `command_summary`
/// metadata so the presenter can set the header without a private text codec.
async fn forward_advisor_progress(
    mut updates: watch::Receiver<OneShotUpdate>,
    progress: ToolProgressSender,
) {
    let initial = updates.borrow().clone();
    if !send_advisor_progress(&progress, &initial).await {
        return;
    }
    while updates.changed().await.is_ok() {
        let update = updates.borrow().clone();
        if !send_advisor_progress(&progress, &update).await {
            return;
        }
    }
}

async fn send_advisor_progress(progress: &ToolProgressSender, update: &OneShotUpdate) -> bool {
    progress.send(advisor_progress_message(update)).await
}

fn advisor_progress_message(update: &OneShotUpdate) -> ToolProgress {
    ToolProgress::message(update.text.to_string())
        .metadata(ToolMetadata::new().command_summary(update.phase.label()))
}

fn execution_error(message: impl Into<String>) -> ToolError {
    ToolError::new(ToolErrorKind::Execution, message)
}

#[cfg(test)]
#[path = "advisor_tests.rs"]
mod tests;