rho-coding-agent 3.1.1

A fast Rust agent harness with a small footprint and opinionated defaults
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
use std::path::{Path, PathBuf};

use rho_sdk::SystemPrompt;
use tracing::Instrument;

use {
    crate::agent::{PromptPolicy, ToolCapability},
    crate::config::Config,
    crate::diagnostics::RuntimeDiagnostics,
    crate::prompt,
    crate::tools::{
        advisor::AdvisorSessionStore,
        sdk_registry::{AppToolSet, DelegationConfig, ToolSetOptions},
    },
};

use super::agent_binding::BoundAgent;

pub(crate) struct ToolsAndPromptOptions<'a> {
    pub(crate) config: &'a Config,
    pub(crate) config_path: PathBuf,
    pub(crate) cwd: &'a Path,
    pub(crate) no_system_prompt: bool,
    pub(crate) no_tools: bool,
    pub(crate) no_subagents: bool,
    pub(crate) questionnaire_enabled: bool,
    /// Whether this run can put an MCP server's question in front of a person.
    /// Only a host that answers questionnaires may declare `elicitation`.
    pub(crate) mcp_elicitation: crate::tools::mcp::McpElicitationSupport,
    /// Whether this run starts MCP servers from user config and Agent Plugins
    /// and loads OpenAPI sources.
    pub(crate) tool_source_attach: ToolSourceAttach,
    /// Whether a configured MCP server may start a browser login. The host
    /// decides: probing stdin here would race the ACP transport's read of it.
    pub(crate) mcp_authorization: crate::tools::mcp::McpAuthorizationMode,
    /// Startup system-prompt model labels should wait on a models.dev
    /// catalog hydrate. Interactive sessions stay cache-only on the first
    /// frame and rewrite once if the hydrate lands before the first request.
    /// Automation stays cache-only so cold/offline launches do not block.
    pub(crate) await_catalog_names: bool,
    /// Interactive sessions spawn MCP connect and OpenAPI loading and paint a
    /// pending inventory so a slow server cannot stall the first frame.
    /// Automation still awaits.
    pub(crate) defer_tool_sources: bool,
    pub(crate) diagnostics: &'a RuntimeDiagnostics,
    pub(crate) agent: &'a BoundAgent,
    /// Added workspace directories: their AGENTS.md files join instruction
    /// discovery, and delegated agents inherit them.
    pub(crate) added_dirs: &'a crate::added_dirs::AddedDirs,
    /// Whether `process start` advertises `keep_warm`. Only a host that runs
    /// the cache warmer that honors it offers it.
    pub(crate) process_keep_warm: crate::tools::process::KeepWarmOffer,
    /// The environment the session's children see.
    pub(crate) environment: crate::session_environment::SessionEnvironment,
    /// Where delegated agents take capacity, and who else hears of them.
    pub(crate) subagent_pool: crate::app::subagent_pool::SubagentPool,
}

/// Whether this session loads external tool sources: MCP servers from user
/// config and Agent Plugins, and OpenAPI sources.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ToolSourceAttach {
    /// Merge plugin MCP into config, connect enabled servers, and load
    /// OpenAPI sources.
    Connect,
    /// Ignore user and plugin MCP and every OpenAPI source. No transports start.
    None,
}

/// When a session that attaches tool sources loads them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ToolSourceLoad {
    /// Before the session opens.
    Inline,
    /// After it opens, so a slow server cannot hold the opening up. The
    /// session's prompts wait for them (see [`DeferredToolSources`]).
    Deferred,
}

/// External tools loaded at session start, together so one deferred job
/// settles them and the prompt and tool list are rebuilt once.
pub(crate) struct ToolSourcesOutcome {
    pub(crate) mcp: crate::tools::mcp::McpConnectOutcome,
    pub(crate) openapi: crate::tools::openapi::bundle::OpenApiLoadOutcome,
}

impl ToolSourcesOutcome {
    /// Connect MCP servers and load OpenAPI sources concurrently.
    async fn load(
        mcp_plan: crate::tools::mcp::McpSessionPlan,
        mcp_config: &crate::tools::mcp::config::McpConfig,
        mcp_options: crate::tools::mcp::McpSessionOptions,
        openapi: crate::tools::openapi::config::SourcePlans,
        openapi_options: crate::tools::openapi::bundle::LoadOptions,
    ) -> Self {
        let (mcp, openapi) = tokio::join!(
            crate::tools::mcp::McpConnectOutcome::run(mcp_plan, mcp_config, mcp_options),
            crate::tools::openapi::bundle::load(openapi, openapi_options),
        );
        Self { mcp, openapi }
    }
}

/// Tool sources a session loads after it opens, as the daemon's sessions
/// do. [`Self::loaded`] says when they finished without a borrow of the
/// session, so its host can wait for them while a turn holds the session.
/// Dropping it stops the load.
pub(crate) struct DeferredToolSources {
    relay: tokio::task::JoinHandle<Result<ToolSourcesOutcome, tokio::task::JoinError>>,
    load: tokio::task::AbortHandle,
    loaded: tokio::sync::watch::Receiver<bool>,
}

impl DeferredToolSources {
    pub(crate) fn follow(load: tokio::task::JoinHandle<ToolSourcesOutcome>) -> Self {
        let (finished, loaded) = tokio::sync::watch::channel(false);
        let abort = load.abort_handle();
        let relay = tokio::spawn(async move {
            let outcome = load.await;
            finished.send_replace(true);
            outcome
        });
        Self {
            relay,
            load: abort,
            loaded,
        }
    }

    /// Resolves once the load finished, or was stopped.
    pub(crate) fn loaded(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
        let mut loaded = self.loaded.clone();
        async move {
            // An error means the relay is gone, so the load is over too.
            let _ = loaded.wait_for(|loaded| *loaded).await;
        }
    }

    pub(crate) fn is_loaded(&self) -> bool {
        *self.loaded.borrow()
    }

    /// Reads `true` once the load finished, without a borrow of the session.
    pub(crate) fn progress(&self) -> tokio::sync::watch::Receiver<bool> {
        self.loaded.clone()
    }

    /// What the load produced. Call once [`Self::is_loaded`].
    pub(crate) async fn outcome(mut self) -> Result<ToolSourcesOutcome, tokio::task::JoinError> {
        match (&mut self.relay).await {
            Ok(outcome) => outcome,
            Err(error) => Err(error),
        }
    }
}

impl Drop for DeferredToolSources {
    fn drop(&mut self) {
        self.load.abort();
        self.relay.abort();
    }
}

/// A session's deferred tool sources, until its runtime runs with them.
pub(crate) enum PendingToolSources {
    /// Still loading, or loaded and not yet attached.
    Loading(DeferredToolSources),
    /// Attached to the session's tool set, but the runtime still runs on
    /// the list it had, since rebuilding it failed. The next attach retries.
    Unbound,
}

pub(crate) struct ToolsAndPrompt {
    pub(crate) tools: AppToolSet,
    /// Stable across tool-list changes, rebuilt when the conversation model changes.
    pub(super) prompt: super::active_prompt::ActivePrompt,
    pub(crate) prompt_template: Option<prompt::ModelPromptTemplate>,
    /// In-flight MCP connect and OpenAPI loading when the interactive host
    /// deferred them off the first frame. `None` when they were awaited or
    /// skipped.
    pub(crate) pending_tool_sources: Option<tokio::task::JoinHandle<ToolSourcesOutcome>>,
}

/// Capability resolution plus system prompt assembly for root interactive and
/// automation startup. Claude-cli agents bind no Rho host tools; root runs still
/// use the Rho loop and parent config, with Claude execution via AgentExecutor
/// for delegated runs.
pub(crate) async fn assemble_tools_and_prompt(
    options: ToolsAndPromptOptions<'_>,
) -> anyhow::Result<ToolsAndPrompt> {
    let native_runtime = options.agent.rho_capabilities().is_some();
    let mut capabilities = options
        .agent
        .rho_capabilities()
        .cloned()
        .unwrap_or_default();
    if options.no_subagents {
        capabilities.remove(&ToolCapability::Agent);
        capabilities.remove(&ToolCapability::Agents);
    }
    if !options.questionnaire_enabled {
        capabilities.remove(&ToolCapability::Questionnaire);
    }
    // The capability says the run may offer the advisor; config says whether it
    // does right now. Advisor mode on with no advisor model configured is a real
    // state, and the TUI surfaces it.
    let advisor_capable = capabilities.contains(&ToolCapability::Advisor);
    let launch_delegation_enabled = capabilities.contains(&ToolCapability::Agent);
    let delegation_enabled =
        launch_delegation_enabled || capabilities.contains(&ToolCapability::Agents);
    // Agent Plugins contribute skills through ordinary skill discovery, MCP
    // servers through the generic native MCP configuration, and agents
    // through the agent catalog's own discovery.
    let project_trust = options.environment.project_trust();
    let plugin_discovery = crate::plugins::discover(
        options.cwd,
        crate::paths::home_dir().as_deref(),
        project_trust,
    );
    crate::plugins::log(&plugin_discovery.report);
    let crate::plugins::PluginDiscovery {
        skills: plugin_skills,
        mcp: plugin_mcp,
        agents: _,
        report: _,
    } = plugin_discovery;
    let mcp_config = mcp_config_for_attach(options.config, plugin_mcp, options.tool_source_attach);
    // One decision for every external tool source, so MCP and OpenAPI attach
    // together or not at all.
    let attach_tool_sources = native_runtime
        && !options.no_tools
        && options.tool_source_attach == ToolSourceAttach::Connect;
    let mcp_plan = if attach_tool_sources {
        crate::tools::mcp::McpSessionPlan::Connect
    } else if !native_runtime {
        crate::tools::mcp::McpSessionPlan::Inventory(
            crate::tools::mcp::McpLoadMode::UnsupportedAgent,
        )
    } else {
        crate::tools::mcp::McpSessionPlan::Inventory(crate::tools::mcp::McpLoadMode::ToolsDisabled)
    };
    // MCP servers and OpenAPI sources take the session's environment as it is
    // when they load (#1659); MCP tool calls send the caller context current
    // when they run (#1765).
    let ambient = options.environment.current();
    let mcp_options = crate::tools::mcp::McpSessionOptions::new(
        options.config.max_output_bytes,
        crate::tools::mcp::McpRoots::for_workspace(options.cwd),
        options.mcp_authorization,
        options.environment.clone(),
    )
    .with_elicitation(options.mcp_elicitation);
    let openapi_plans = if attach_tool_sources {
        crate::tools::openapi::config::OpenApiSources::discover(
            &options.config.openapi,
            &options.config_path,
            options.cwd,
            project_trust.openapi,
        )
        .plan(&|name| ambient.read(name))
    } else {
        crate::tools::openapi::config::SourcePlans::default()
    };
    let openapi_options =
        crate::tools::openapi::bundle::LoadOptions::new(options.config.max_output_bytes);
    // A source that failed planning still defers, so its error reaches the
    // transcript through the same path as a failed download.
    let defer = options.defer_tool_sources
        && attach_tool_sources
        && (mcp_config.has_enabled_servers() || !openapi_plans.is_empty());
    let (sources, pending_tool_sources) = if defer {
        let pending_report =
            crate::tools::mcp::McpSessionReport::from_config_connecting(&mcp_config);
        let connect_config = mcp_config.clone();
        let connect_options = mcp_options.clone();
        let handle = tokio::spawn(
            async move {
                ToolSourcesOutcome::load(
                    crate::tools::mcp::McpSessionPlan::Connect,
                    &connect_config,
                    connect_options,
                    openapi_plans,
                    openapi_options,
                )
                .await
            }
            .instrument(tracing::info_span!("startup.tool_sources")),
        );
        let pending = ToolSourcesOutcome {
            mcp: crate::tools::mcp::McpConnectOutcome {
                report: pending_report,
                bundle: None,
                catalog: crate::tools::mcp::McpCatalog::default(),
            },
            openapi: crate::tools::openapi::bundle::OpenApiLoadOutcome::default(),
        };
        (pending, Some(handle))
    } else {
        let loaded = ToolSourcesOutcome::load(
            mcp_plan,
            &mcp_config,
            mcp_options,
            openapi_plans,
            openapi_options,
        )
        .await;
        // Hosts that load inline have no transcript yet, so problems go to
        // the log, as MCP connect failures do. Deferred loads show them.
        for problem in loaded
            .openapi
            .report
            .errors
            .iter()
            .chain(&loaded.openapi.report.warnings)
        {
            tracing::warn!("{problem}");
        }
        (loaded, None)
    };
    let ToolSourcesOutcome { mcp, openapi } = sources;
    let mut tools = if options.no_tools {
        AppToolSet::disabled_for(options.environment.credentials()).with_mcp(mcp)
    } else {
        let mut tool_options = ToolSetOptions::new(capabilities)
            .process_keep_warm(options.process_keep_warm)
            .environment(options.environment.clone());
        let workflow_tracker = crate::tools::workflow_tracker::WorkflowRunTracker::new();
        tool_options = tool_options.workflow_tracker(workflow_tracker.clone());
        if advisor_capable {
            tool_options = tool_options.advisor(AdvisorSessionStore::new());
        }
        if delegation_enabled {
            tool_options = tool_options.delegation(DelegationConfig::new(
                options.cwd.to_path_buf(),
                options.config_path.clone(),
                /*catalog*/ None,
                options.subagent_pool.clone(),
            ));
        }
        if options
            .agent
            .rho_capabilities()
            .is_some_and(|capabilities| capabilities.contains(&ToolCapability::Workflow))
        {
            tool_options = tool_options.workflow(super::workflow_cli::workflow_tool_service(
                options.cwd.to_path_buf(),
                Some(options.config_path.clone()),
                workflow_tracker,
                options.subagent_pool.clone(),
                options.environment.clone(),
            ));
        }
        AppToolSet::new(options.config, options.diagnostics.clone(), tool_options).with_mcp(mcp)
    };
    tools.attach_openapi(openapi);
    if let Some(manager) = tools.subagents() {
        manager.update_added_dirs(options.added_dirs.clone());
    }
    let mcp_report = tools.mcp_report().clone();
    let openapi_report = tools.openapi_report().clone();
    let specs = tools.specs();
    let mut prompt_template = None;
    let mut model_prompt = None;
    let mut sources = Vec::new();
    let system_prompt = if options.no_system_prompt {
        SystemPrompt::None
    } else {
        let mut text = match options.agent.prompt() {
            PromptPolicy::Replace(text) => text.clone(),
            PromptPolicy::Extend(extra) => {
                // The bound model, not the host one: a delegated agent that
                // pins its own model must be told the model it is running on.
                let running = options.agent.prompt_model();
                let advisor = advisor_capable
                    .then(|| crate::tools::advisor::advisor_model(options.config))
                    .flatten()
                    .map(crate::model_identity::PromptModel::from_internal_agent);
                // Interactive sessions stay cache-only on the first frame. A
                // later one-shot rewrite can land display names if hydrate
                // finishes before the first request. Automation stays cache-only.
                if options.await_catalog_names {
                    rho_providers::model::ensure_model_catalog_names().await;
                }
                let mut template = prompt::system_prompt_template_with_plugin_skills(
                    &specs,
                    options.cwd,
                    advisor.as_ref(),
                    plugin_skills,
                );
                template.replace_tool_sources(&mcp_report, &openapi_report);
                template.set_added_dirs(options.added_dirs);
                let mut retained = String::new();
                if !launch_delegation_enabled {
                    prompt::append_subagents_disabled_instruction(&mut retained);
                }
                if !extra.is_empty() {
                    retained.push_str(&format!("\n\n# Agent instructions\n\n{extra}"));
                }
                template.append_retained(&retained);
                let built = match template.build(&running) {
                    Ok(built) => built,
                    Err(error) => {
                        if let Some(pending) = pending_tool_sources {
                            pending.abort();
                        }
                        tools.shutdown().await;
                        return Err(error);
                    }
                };
                sources = built.sources;
                prompt_template = Some(template);
                model_prompt = built.model_prompt;
                built.text
            }
        };
        if text.is_empty() {
            text = "You are a coding agent.".into();
        }
        // Advisor steering lives on the tool description / enable notice, not
        // here, so mid-session /advisor toggles never require a prompt rewrite.
        SystemPrompt::Custom(text)
    };
    let prompt = super::active_prompt::ActivePrompt::new(system_prompt, model_prompt, sources);
    prompt.install(options.diagnostics, tools.advisor());
    options.diagnostics.update_tools(&specs);
    Ok(ToolsAndPrompt {
        tools,
        prompt,
        prompt_template,
        pending_tool_sources,
    })
}

pub(super) fn mcp_config_for_attach(
    config: &Config,
    plugin_mcp: crate::tools::mcp::config::McpConfig,
    attach: ToolSourceAttach,
) -> crate::tools::mcp::config::McpConfig {
    match attach {
        ToolSourceAttach::None => crate::tools::mcp::config::McpConfig::default(),
        ToolSourceAttach::Connect => {
            let mut mcp_config = config.mcp.clone();
            mcp_config.merge(plugin_mcp);
            mcp_config
        }
    }
}

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