rho-coding-agent 3.12.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
//! Agent binding and restoration for host-created children: `/agent:<name>`
//! rebinds a fresh session to a delegated agent, and a reload binds it as
//! that child again.

use std::{future::Future, sync::Arc};

use rho_sdk::{SessionOptions, UserInput};
use serde::{Deserialize, Serialize};

use super::{
    build::{build_session, mcp_discovery, session_config},
    model_scoped_config,
    open::session_options_for_id,
    CommandRejected, PromptScope, SessionPermission, SessionRuntime, SessionUse,
};
use crate::{
    agent::{AgentCatalog, AgentDefinition},
    app::{
        agent_binding::{AgentBinder, AgentInvocation, AgentRole, BoundAgent, ModelOverride},
        agent_reopen::{reopened, Instructions},
        session_assembly::BuiltSession,
        tools_prompt::ToolSourceLoad,
    },
    config::Config,
    session::Session as StoredSession,
};

/// Resolved selection, not the alias or definition: alias edits must not move
/// a resumed call to another provider. Auth is a profile id, never a credential.
/// The key predates the runtime and names ACP, which first hosted children.
pub(in crate::app) const MODEL_OVERRIDE_METADATA: &str = "rho.acp.agent_model_override";

/// `/agent:<name>`: a task for a delegated agent, whose per-call model
/// selection stays separate from the definition.
#[derive(Debug, PartialEq)]
pub(crate) struct AgentTask {
    pub(crate) agent_id: String,
    pub(crate) model_override: Option<String>,
    pub(crate) input: UserInput,
}

#[derive(Deserialize, Serialize)]
struct SavedModelOverride {
    provider: String,
    model: String,
    auth: String,
}

/// The model a delegated session's file keeps as its call's override, if
/// it keeps one that reads.
pub(super) fn saved_model_override(stored: &StoredSession) -> Option<super::CurrentModel> {
    let encoded = stored.session_metadata(MODEL_OVERRIDE_METADATA).ok()??;
    let SavedModelOverride {
        provider,
        model,
        auth,
    } = serde_json::from_str(&encoded).ok()?;
    Some(super::CurrentModel {
        provider,
        model,
        auth,
    })
}

/// A later host-selected model supersedes the launch override. Keep the marker
/// and concrete selection together at every durable save, including step saves.
pub(super) fn decorate_model_override(
    snapshot: rho_sdk::SessionSnapshot,
    auth: &str,
) -> rho_sdk::SessionSnapshot {
    if !snapshot.metadata().contains_key(MODEL_OVERRIDE_METADATA) {
        return snapshot;
    }
    let identity = snapshot.provider();
    let saved = SavedModelOverride {
        provider: identity.provider.clone(),
        model: identity.model.clone(),
        auth: auth.to_owned(),
    };
    snapshot.with_metadata(
        MODEL_OVERRIDE_METADATA,
        serde_json::to_string(&saved).expect("model selection contains only strings"),
    )
}

impl SessionRuntime {
    /// A host-selected replacement must be bindable on the next load. Validate
    /// through the same definition policy before touching live or saved state.
    pub(super) fn validate_model_override_switch(&self, config: &Config) -> anyhow::Result<()> {
        if !self
            .built
            .session
            .snapshot()
            .metadata()
            .contains_key(MODEL_OVERRIDE_METADATA)
        {
            return Ok(());
        }
        let chosen = config.require_conversation_model()?;
        AgentBinder::bind_with_credentials(
            Arc::new(self.agent.definition().clone()),
            AgentInvocation {
                role: AgentRole::Delegated,
                available_tools: self.agent.rho_capabilities().cloned().unwrap_or_default(),
            },
            config,
            Some(ModelOverride::Saved {
                provider: &chosen.provider,
                model: &chosen.model,
                auth: &chosen.auth,
            }),
            self.build.host.environment.credentials().as_ref(),
        )?;
        Ok(())
    }

    /// A host model change replaces a call override even without another turn.
    /// Ordinary roots keep their existing reload policy and deferred files.
    pub(super) fn persist_model_override(&self) -> anyhow::Result<()> {
        // A session opened only to be read saves nothing, though reopening
        // switches it to the model its file keeps.
        if self.build.host.session_use == SessionUse::Read {
            return Ok(());
        }
        let Some(stored) = self.storage.file() else {
            return Ok(());
        };
        let snapshot = self.durable_snapshot();
        if snapshot.metadata().contains_key(MODEL_OVERRIDE_METADATA) {
            stored.save_snapshot(&snapshot, &[])?;
        }
        Ok(())
    }

    /// Rebuilds a fresh child for `task` within `prompt`, with its selected
    /// model and definition's prompt and tools. The host then submits only
    /// the task to the model as the prompt's turn; the original command
    /// remains in display history so the host can show how the child was
    /// launched.
    pub(crate) async fn rebind_agent(
        &mut self,
        prompt: &PromptScope,
        task: &AgentTask,
        process_config: &Config,
    ) -> anyhow::Result<()> {
        let catalog = AgentCatalog::discover(
            self.storage.cwd(),
            self.build.host.environment.project_trust(),
        )?;
        let definition = catalog.find(&task.agent_id)?.definition.clone();
        let model_override = task.model_override.clone();
        let cwd = self.storage.cwd().to_path_buf();
        let added_dirs = self.added_dirs.clone();
        let build = self.build.clone();
        let host_mcp = self.host_mcp.clone();
        self.rebind_agent_with(
            prompt,
            task,
            process_config,
            |base| {
                bind_delegated_agent(
                    definition,
                    model_override.as_deref().map(ModelOverride::Reference),
                    &build.launch.agent,
                    base,
                    build.host.environment.credentials().as_ref(),
                )
            },
            async |agent, config, id| {
                Box::pin(build_session(
                    &build,
                    &agent,
                    &config,
                    &cwd,
                    &added_dirs,
                    // A rebind runs within a prompt, which must find its
                    // tools there.
                    ToolSourceLoad::Inline,
                    |_| Ok(session_options_for_id(id)),
                ))
                .await
                .inspect(|(built, _)| {
                    built
                        .tools
                        .mcp_host()
                        .set_discovery(mcp_discovery(&build, &host_mcp, &cwd));
                })
            },
        )
        .await
    }

    /// Keep the rebind transaction independent of credential/provider discovery
    /// so its session and tool restrictions can use a scripted build in tests.
    /// `build` builds as [`build_session`] does. `_prompt` only proves the
    /// rebind runs within a prompt, whose turn the child then takes.
    pub(crate) async fn rebind_agent_with<Build, BuildFuture>(
        &mut self,
        _prompt: &PromptScope,
        task: &AgentTask,
        process_config: &Config,
        bind: impl FnOnce(&Config) -> anyhow::Result<BoundAgent>,
        build: Build,
    ) -> anyhow::Result<()>
    where
        Build: FnOnce(BoundAgent, Config, rho_sdk::SessionId) -> BuildFuture,
        BuildFuture: Future<Output = anyhow::Result<(BuiltSession, SessionPermission)>>,
    {
        // A conversation must survive, never be dropped.
        if self.completed_runs != 0 || self.has_conversation() {
            return Err(CommandRejected(
                "/agent:<name> starts a fresh session only; create a new session".into(),
            )
            .into());
        }

        // A host may select a model, mode and thought level before the first
        // prompt, as T3 Code does.
        let mut base = model_scoped_config(&self.current_model(), process_config);
        base.permission_mode = self.permission.mode;
        base.reasoning = self.built.session.reasoning_level();
        let bound = bind(&base)?;
        let config = session_config(
            bound.rho_config().ok_or_else(|| not_a_rho_agent(&bound))?,
            &self.host_mcp,
        );
        let id = self.built.session.id().clone();
        let chosen = config.require_conversation_model()?.clone();
        let saved_override = task
            .model_override
            .as_ref()
            .map(|_| {
                serde_json::to_string(&SavedModelOverride {
                    provider: chosen.provider.clone(),
                    model: chosen.model.clone(),
                    auth: chosen.auth.clone(),
                })
            })
            .transpose()?;
        let (mut built, permission) = build(bound.clone(), config.clone(), id).await?;
        if let Some(saved) = saved_override {
            let snapshot = built
                .session
                .snapshot()
                .with_metadata(MODEL_OVERRIDE_METADATA, saved);
            // SDK snapshot metadata survives checkpoints, compaction and mode
            // rebinds. Seed it before the first turn can save a checkpoint.
            match built
                .runtime
                .rebind_session(SessionOptions::from_snapshot(snapshot))
                .await
            {
                Ok(session) => built.session = session,
                Err(error) => {
                    built.teardown().await;
                    return Err(error.into());
                }
            }
        }
        // Publish the concrete selection and delegated identity in one durable
        // replacement, before teardown or host notifications can suspend us.
        let initial_snapshot = task.model_override.as_ref().map(|_| {
            super::persist::DurableState {
                prompt: built.prompt.clone(),
                todo: built.tools.todo_state(),
                code_mode: built.tools.code_mode().clone(),
                added_dirs: self.added_dirs.clone(),
                left_out: self.build.launch.left_out,
                host_prompt: self.build.launch.host_prompt.clone(),
                auth: chosen.auth.clone(),
                // As before the rebind; the next save records the rebound
                // session's.
                settings: self.settings_record(),
                started_sessions: self.started_sessions.clone(),
            }
            .decorate(built.session.snapshot())
        });
        // An ephemeral session has no file to record the rebind on.
        let rebound = self.stored().and_then(|stored| {
            stored.map_or(Ok(()), |stored| {
                stored.rebind_fresh_delegated_agent(&bound.saved(), initial_snapshot.as_ref())
            })
        });
        if let Err(error) = rebound {
            built.teardown().await;
            return Err(error);
        }
        let old = std::mem::replace(&mut self.built, built);
        old.teardown().await;
        self.permission = permission;
        self.auth = chosen.auth;
        self.auth_origin = chosen.auth_origin;
        tracing::debug!(previous = %self.agent.id(), agent = %bound.id(), "rebound session agent");
        self.agent = bound;
        self.built.tools.bind_recall(self.storage.file());
        // The rebuilt tools hold new subagents.
        self.send_child_questions_to_host();
        Ok(())
    }
}

/// The agent and config a loaded session runs with. Roots run as
/// `launch_agent`; a session `/agent:` rebound is marked delegated, so it
/// binds as that child again, capped at `launch_agent`'s tools, with the
/// child's current definition and the instructions it was rebound with (see
/// `agent_reopen::reopened`). A missing child fails the load rather than
/// widening the child to the root's tools. The host picks
/// `launch_agent`: the daemon binds the root the session was rebound from
/// (see its `bind_saved_agent`), ACP its process's launch agent. `catalog`
/// discovers definitions only for delegated sessions, which bind with the
/// session's `credentials`.
pub(super) fn loaded_agent(
    launch_agent: &BoundAgent,
    stored: &StoredSession,
    config: Config,
    catalog: impl FnOnce() -> anyhow::Result<AgentCatalog>,
    credentials: &dyn rho_providers::credentials::CredentialStore,
) -> anyhow::Result<(BoundAgent, Config)> {
    loaded_agent_with(
        launch_agent,
        stored,
        config,
        catalog,
        |definition, model_override, launch_agent, base| {
            bind_delegated_agent(definition, model_override, launch_agent, base, credentials)
        },
    )
}

/// Keep credential discovery injectable while testing durable selection and
/// definition-identity checks at the load boundary.
pub(in crate::app) fn loaded_agent_with(
    launch_agent: &BoundAgent,
    stored: &StoredSession,
    config: Config,
    catalog: impl FnOnce() -> anyhow::Result<AgentCatalog>,
    bind: impl FnOnce(
        AgentDefinition,
        Option<ModelOverride<'_>>,
        &BoundAgent,
        &Config,
    ) -> anyhow::Result<BoundAgent>,
) -> anyhow::Result<(BoundAgent, Config)> {
    // The persisted role, not the id, decides: a child may share the launch
    // agent's id and must still reload with its delegated tool boundary.
    let Some(saved) = stored.delegated_agent()? else {
        return Ok((launch_agent.clone(), config));
    };
    // The child's current definition, with the instructions the session
    // was rebound with.
    let catalog = catalog()?;
    let current = &catalog.find(&saved.id)?.definition;
    let read = || stored.stored_system_prompt();
    let definition = reopened(&saved, current, Instructions::Rendered(&read))?;
    let stored_id = saved.id;
    let model_override = stored
        .session_metadata(MODEL_OVERRIDE_METADATA)?
        .map(|encoded| serde_json::from_str::<SavedModelOverride>(&encoded))
        .transpose()?;
    let selection = model_override.as_ref().map(|saved| ModelOverride::Saved {
        provider: &saved.provider,
        model: &saved.model,
        auth: &saved.auth,
    });
    let bound = bind(definition, selection, launch_agent, &config)?;
    let config = bound
        .rho_config()
        .cloned()
        .ok_or_else(|| not_a_rho_agent(&bound))?;
    if let Some(saved) = model_override {
        let chosen = config.require_conversation_model()?;
        anyhow::ensure!(
            (chosen.provider.as_str(), chosen.model.as_str(), chosen.auth.as_str())
                == (saved.provider.as_str(), saved.model.as_str(), saved.auth.as_str()),
            "agent '{stored_id}': saved model override {}/{} with auth '{}' resolved to {}/{} with auth '{}'; refusing to change the resumed selection",
            saved.provider, saved.model, saved.auth, chosen.provider, chosen.model, chosen.auth,
        );
    }
    Ok((bound, config))
}

/// Both fresh rebinding and resume must enforce the delegated tool boundary:
/// the child gets at most `launch_agent`'s tools. Callers refuse a bound
/// agent that does not run on Rho.
pub(in crate::app) fn bind_delegated_agent(
    definition: AgentDefinition,
    model_override: Option<ModelOverride<'_>>,
    launch_agent: &BoundAgent,
    base: &Config,
    credentials: &dyn rho_providers::credentials::CredentialStore,
) -> anyhow::Result<BoundAgent> {
    AgentBinder::bind_with_credentials(
        Arc::new(definition),
        AgentInvocation {
            role: AgentRole::Delegated,
            available_tools: launch_agent.rho_capabilities().cloned().unwrap_or_default(),
        },
        base,
        model_override,
        credentials,
    )
}

/// Why a session cannot run `bound`: it runs on another runtime, such as
/// Claude Code.
fn not_a_rho_agent(bound: &BoundAgent) -> CommandRejected {
    CommandRejected(format!(
        "{} runs on {}, which a Rho session cannot run",
        bound.id(),
        bound.definition().runtime.runtime()
    ))
}

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