rho-coding-agent 3.4.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! Shared startup path for non-interactive Rho sessions.
//!
//! Automation runs and ACP sessions both need the same assembly: provider,
//! workspace, tools and prompt, approval wiring, hooks, runtime, and session.
//! They differ only in the tool and prompt deltas, the approval recipe, and the
//! session options, so those arrive as call-site policy.

use std::{
    borrow::Cow,
    num::NonZeroUsize,
    path::{Path, PathBuf},
    sync::Arc,
};

use rho_providers::{
    auth::provider_credentials::ApplicationCredentialSource,
    model::ModelError,
    providers::{build_automation_provider, UnavailableProvider},
};
use rho_sdk::{
    model::ModelIdentity, provider::ModelProvider, ApprovalRequestReceiver, ApprovalSession,
    Session, SessionOptions,
};

use super::{
    agent_binding::BoundAgent,
    policy::AppPolicy,
    runtime_builder::{
        build_runtime_with_max_steps, configured_context_window, RuntimeBuildOptions,
    },
    sdk_config::SdkBootstrapOptions,
    tools_prompt::{assemble_tools_and_prompt, ToolsAndPrompt, ToolsAndPromptOptions},
};
use crate::{
    config::Config, diagnostics::RuntimeDiagnostics, permission::SessionWriteLog,
    tools::sdk_registry::AppToolSet,
};

/// Everything a caller must supply to assemble a session, including the three
/// policy hooks that differ between callers.
pub(super) struct SessionAssemblyOptions<'a, ExtendTools, Approval, Options> {
    pub config: &'a Config,
    pub config_path: PathBuf,
    pub cwd: &'a Path,
    pub no_system_prompt: bool,
    pub no_tools: bool,
    pub no_subagents: bool,
    pub questionnaire_enabled: bool,
    /// The session's A2UI surfaces, when its host's clients draw them.
    pub(crate) surfaces: Option<crate::tools::ui::SurfaceHost>,
    /// The session's side of the daemon's pull request service.
    pub(crate) pull_requests: Option<crate::app::pull_requests::PullRequestInbox>,
    pub mcp_elicitation: crate::tools::mcp::McpElicitationSupport,
    pub tool_source_attach: super::tools_prompt::ToolSourceAttach,
    pub tool_source_load: super::tools_prompt::ToolSourceLoad,
    /// Whether the session starts its workspace's hooks.
    pub hook_start: HookStart,
    /// Whether the session must sign in to its model.
    pub sign_in: SignIn,
    pub mcp_authorization: crate::tools::mcp::McpAuthorizationMode,
    pub diagnostics: &'a RuntimeDiagnostics,
    pub agent: &'a BoundAgent,
    pub max_steps: Option<NonZeroUsize>,
    pub usage_purpose: &'static str,
    pub usage_parent_session_id: Option<rho_sdk::SessionId>,
    pub hook_host_labels: rho_sdk::hooks::HookHostLabels,
    /// Directories added to the workspace scope beyond `cwd`.
    pub added_dirs: &'a crate::added_dirs::AddedDirs,
    /// The environment the session's children see.
    pub environment: crate::session_environment::SessionEnvironment,
    /// Where delegated agents take capacity, and who else hears of them.
    pub subagent_pool: crate::app::subagent_pool::SubagentPool,
    /// Whether `process start` offers `keep_warm`: only under a host that
    /// runs a cache warmer.
    pub process_keep_warm: crate::tools::process::KeepWarmOffer,
    /// Adds caller-owned tools after shared assembly.
    pub extend_tools: ExtendTools,
    /// Host instructions retained across model-specific behavioral replacement.
    pub system_prompt_suffix: Option<&'a str>,
    /// Builds the approval wiring for this caller's permission story.
    pub approval: Approval,
    /// Chooses the session options once the provider is known.
    pub session_options: Options,
}

/// Whether an assembled session must sign in to its model.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SignIn {
    /// Assembly fails when the model's credential is missing.
    Required,
    /// The session may open without it, when it is only read or its client
    /// signs in later: a model that cannot be signed in to is stood in for
    /// by one that fails every request.
    Optional,
}

/// Whether an assembled session starts its workspace's hooks.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum HookStart {
    /// Starts them, so they hear the session's events from its start.
    Start,
    /// Starts none: the session is only read, so nothing of it runs.
    Skip,
}

/// Inputs an approval recipe needs; all are produced during assembly.
pub(super) struct ApprovalInputs {
    pub config: Config,
    pub workspace_root: PathBuf,
    pub usage_recording: rho_sdk::ProviderRequestUsageRecording,
    pub session_writes: SessionWriteLog,
    /// The session's credentials, which Auto's classifier signs in with.
    pub credentials: Arc<dyn rho_providers::credentials::CredentialStore>,
}

/// Approval wiring for one session: the handler the runtime enforces and, for
/// hosts that answer prompts themselves, the receiving end of the channel.
pub(super) struct SessionApproval {
    pub session: Option<ApprovalSession>,
    pub receiver: Option<ApprovalRequestReceiver>,
}

/// A live session plus the pieces its owner must shut down.
pub(super) struct BuiltSession {
    pub runtime: rho_sdk::Rho,
    pub session: Session,
    pub provider: Arc<dyn ModelProvider>,
    pub tools: AppToolSet,
    pub hooks: Option<crate::hooks::HookPipeline>,
    pub approval_receiver: Option<ApprovalRequestReceiver>,
    pub prompt_template: Option<crate::prompt::ModelPromptTemplate>,
    pub prompt: super::active_prompt::ActivePrompt,
    pub diagnostics: RuntimeDiagnostics,
    /// The tool sources still loading, when the session defers them.
    pub tool_sources: Option<super::tools_prompt::PendingToolSources>,
    /// Whether `provider` was built from the model's credentials.
    pub provider_credentials: ProviderCredentials,
}

/// Whether an assembled session's provider was built from its model's
/// credentials, or stands in for one that could not be ([`SignIn::Optional`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ProviderCredentials {
    Found,
    Missing,
}

impl BuiltSession {
    /// Shuts the runtime down first so in-flight work stops before the hook
    /// pipeline drains and the tool hosts close.
    pub(super) async fn teardown(self) {
        let Self {
            runtime,
            session,
            tools,
            hooks,
            ..
        } = self;
        runtime.shutdown();
        drop(session);
        drop(runtime);
        teardown_startup(hooks, tools).await;
    }
}

/// Releases the pieces that exist when startup fails before a session does.
async fn teardown_startup(hooks: Option<crate::hooks::HookPipeline>, tools: AppToolSet) {
    if let Some(hooks) = hooks {
        hooks.shutdown(crate::hooks::DRAIN_GRACE).await;
    }
    tools.shutdown().await;
}

/// An assembled session and the workspace root it resolved to.
pub(super) struct SessionAssembly {
    pub built: BuiltSession,
    pub workspace_root: PathBuf,
    /// Write grants the session's policy remembers. A host that later swaps
    /// the permission mode carries or drops these with the new mode.
    pub session_writes: SessionWriteLog,
}

pub(super) async fn assemble_session<ExtendTools, Approval, Options>(
    options: SessionAssemblyOptions<'_, ExtendTools, Approval, Options>,
) -> anyhow::Result<SessionAssembly>
where
    ExtendTools: FnOnce(AppToolSet) -> AppToolSet,
    Approval: FnOnce(ApprovalInputs) -> anyhow::Result<SessionApproval>,
    Options: FnOnce(Arc<dyn ModelProvider>) -> anyhow::Result<SessionOptions>,
{
    let SessionAssemblyOptions {
        config,
        config_path,
        cwd,
        no_system_prompt,
        no_tools,
        no_subagents,
        questionnaire_enabled,
        surfaces,
        pull_requests,
        mcp_elicitation,
        tool_source_attach,
        tool_source_load,
        hook_start,
        sign_in,
        mcp_authorization,
        diagnostics,
        agent,
        max_steps,
        usage_purpose,
        usage_parent_session_id,
        hook_host_labels,
        added_dirs,
        environment,
        subagent_pool,
        process_keep_warm,
        extend_tools,
        system_prompt_suffix,
        approval,
        session_options,
    } = options;
    // A host logged in through its endpoint (Ollama) and not logged in is
    // missing its credential like a provider without a key.
    let (login_config, missing_login) =
        match super::endpoint_login::with_disk_login(config, &config_path) {
            Ok(login_config) => (login_config, None),
            Err(error) => match (error.downcast::<ModelError>(), sign_in) {
                (Ok(missing), SignIn::Optional) => (Cow::Borrowed(config), Some(missing)),
                (Ok(missing), SignIn::Required) => return Err(missing.into()),
                (Err(error), _) => return Err(error),
            },
        };
    // from_config already scopes custom-provider resolution. Do not hold a
    // thread-local overlay across the catalog await: Tokio may resume on
    // another worker and Drop would pop the wrong stack.
    let sdk_options = SdkBootstrapOptions::from_config(&login_config, cwd)?;
    let credentials = ApplicationCredentialSource::new(environment.credentials());
    let built = match missing_login {
        Some(missing) => Err(missing),
        None => {
            // Automation and ACP normally skip the catalog fetch, but
            // catalog-constructed providers need the hydrate before build; a
            // no-op for the rest.
            sdk_options.provider.ensure_catalog_for_construction().await;
            build_automation_provider(sdk_options.provider, &credentials)
        }
    };
    let (provider, provider_credentials) = match (built, sign_in) {
        (Ok(provider), _) => (provider, ProviderCredentials::Found),
        (Err(error), SignIn::Required) => return Err(error.into()),
        (Err(error), SignIn::Optional) => (
            Arc::new(UnavailableProvider::standing_in_for(
                ModelIdentity::new(&login_config.provider, "unavailable", &login_config.model),
                error,
            )) as Arc<dyn ModelProvider>,
            ProviderCredentials::Missing,
        ),
    };
    let live_provider = Arc::clone(&provider);
    let workspace_root = sdk_options.workspace.root.clone();
    let workspace = sdk_options.workspace.build_workspace(added_dirs)?;
    let ToolsAndPrompt {
        tools: tool_set,
        mut prompt,
        mut prompt_template,
        pending_tool_sources,
    } = assemble_tools_and_prompt(ToolsAndPromptOptions {
        config,
        config_path,
        cwd,
        no_system_prompt,
        no_tools,
        no_subagents,
        questionnaire_enabled,
        surfaces,
        pull_requests,
        mcp_elicitation,
        tool_source_attach,
        mcp_authorization,
        await_catalog_names: false,
        defer_tool_sources: match tool_source_load {
            super::tools_prompt::ToolSourceLoad::Inline => false,
            super::tools_prompt::ToolSourceLoad::Deferred => true,
        },
        diagnostics,
        agent,
        added_dirs,
        process_keep_warm,
        environment: environment.clone(),
        subagent_pool,
    })
    .await?;
    // Wrapped at once, so a failure below stops the load as it drops.
    let tool_sources = pending_tool_sources.map(|load| {
        super::tools_prompt::PendingToolSources::Loading(
            super::tools_prompt::DeferredToolSources::follow(load),
        )
    });
    let tool_set = extend_tools(tool_set);
    if let Some(suffix) = system_prompt_suffix {
        let retained = format!("\n\n{suffix}");
        prompt.append_retained(&retained);
        if let Some(template) = prompt_template.as_mut() {
            template.append_retained(&retained);
        }
    }
    let resumed_prompt = prompt_template.as_ref().and_then(|_| match &prompt.system {
        rho_sdk::SystemPrompt::Custom(text) => Some(text.clone()),
        _ => None,
    });

    let context_window = configured_context_window(config);
    let compaction = sdk_options.runtime.compaction.clone();
    diagnostics.update_compaction_config(&compaction);
    let usage_recording = crate::usage::default_recording().await;
    let session_writes = SessionWriteLog::default();
    let SessionApproval {
        session: approval_session,
        receiver: approval_receiver,
    } = approval(ApprovalInputs {
        config: config.clone(),
        workspace_root: workspace_root.clone(),
        usage_recording: usage_recording.clone(),
        session_writes: session_writes.clone(),
        credentials: environment.credentials(),
    })?;
    let search_path = environment.current().path();
    let hooks = match hook_start {
        HookStart::Start => crate::hooks::start_for_cwd(&workspace_root, environment),
        HookStart::Skip => None,
    };
    if let Some(hooks) = hooks.as_ref() {
        diagnostics.attach_hooks(hooks);
    }
    let session_options = match session_options(provider.clone()) {
        Ok(options) => options,
        Err(error) => {
            teardown_startup(hooks, tool_set).await;
            return Err(error);
        }
    };
    let startup_result: anyhow::Result<_> = async {
        let runtime = build_runtime_with_max_steps(
            RuntimeBuildOptions {
                provider: Arc::clone(&provider),
                tools: &tool_set,
                workspace,
                workspace_policy: AppPolicy::for_mode(
                    config.permission_mode,
                    session_writes.clone(),
                    search_path,
                ),
                approval_session,
                system_prompt: prompt.system.clone(),
                reasoning: sdk_options.runtime.reasoning,
                service_tier: sdk_options.runtime.service_tier,
                compaction,
                context_window,
                usage_purpose,
                usage_parent_session_id,
                usage_recording,
                hook_host_labels,
                hooks: hooks.as_ref(),
                diagnostics: diagnostics.clone(),
                recall: tool_set.recall_store(),
            },
            max_steps,
        )?;
        let session = match runtime.session(session_options).await {
            Ok(session) => session,
            Err(error) => {
                runtime.shutdown();
                return Err(error.into());
            }
        };
        if let Some(text) = resumed_prompt {
            if let Err(error) = super::conversation_switch::replace_system_prompt(&session, &text) {
                runtime.shutdown();
                return Err(error.into());
            }
        }
        anyhow::Ok((runtime, session))
    }
    .await;
    let (runtime, session) = match startup_result {
        Ok(startup) => startup,
        Err(error) => {
            teardown_startup(hooks, tool_set).await;
            return Err(error);
        }
    };
    tool_set.bind_session_search(session.id().as_str());
    let snapshot = session.snapshot();
    tool_set.todo_state().restore(&snapshot);
    tool_set.code_mode().restore(&snapshot);
    if let Some(advisor) = tool_set.advisor() {
        advisor.bind_session(session.clone());
    }
    // Host suffixes are appended after tool assembly. Reinstall the complete
    // prompt so the advisor sees the same retained host instructions.
    prompt.install(diagnostics, tool_set.advisor());
    Ok(SessionAssembly {
        built: BuiltSession {
            runtime,
            session,
            provider: live_provider,
            tools: tool_set,
            hooks,
            approval_receiver,
            prompt_template,
            prompt,
            diagnostics: diagnostics.clone(),
            tool_sources,
            provider_credentials,
        },
        workspace_root,
        session_writes,
    })
}