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
417
418
419
420
421
//! Runtimes for tests: a plain root agent with every tool, on scripted
//! sessions that need no credentials.

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

use rho_sdk::{
    model::{ModelIdentity, ModelRequest},
    provider::{ModelProvider, ProviderFuture, ScriptedProvider},
    SessionOptions,
};

use super::{
    credentials::SessionCredentials, started_sessions::STARTED_SESSION_DEFAULTS_METADATA,
    ApprovalPolicy, ChildAgents, HostCapabilities, LeftOut, OpenedSession, QuestionSupport,
    RunShape, SessionBuild, SessionLaunch, SessionPermission, SessionRole, SessionRuntime,
    SessionStorage, StartedSessions, UnattendedApprovals,
};
use crate::{
    agent::{
        AgentCapabilities, AgentDefinition, AgentId, AgentRuntimeSpec, ModelPolicy, PromptPolicy,
        ToolPolicy,
    },
    app::{
        agent_binding::{AgentBinder, AgentInvocation, AgentRole, BoundAgent},
        pull_requests::PullRequestInbox,
        session_assembly::BuiltSession,
    },
    config::Config,
    diagnostics::RuntimeDiagnostics,
    session::Session as StoredSession,
    tools::{mcp::McpAuthorizationMode, sdk_registry::AppToolSet},
};

/// A plain root agent, `rho`, with every host tool, bound on `config`.
pub(super) fn root_agent(config: &Config) -> BoundAgent {
    AgentBinder::bind(
        Arc::new(AgentDefinition {
            id: AgentId::new("rho").expect("test agent id"),
            description: "test".into(),
            prompt: PromptPolicy::Extend(String::new()),
            runtime: AgentRuntimeSpec::Rho {
                tools: ToolPolicy::All,
                model: ModelPolicy::Inherit,
                reasoning: None,
            },
            starter_hears: crate::agent::StarterHears::TurnEnds,
            session_model: crate::agent::SessionModel::StartedSessions,
        }),
        AgentInvocation {
            role: AgentRole::AutomationRoot,
            available_tools: AgentCapabilities::all_host_tools(),
        },
        config,
    )
    .expect("bind test agent")
}

/// A provider on `config`'s model with no scripted turns.
fn idle_provider(config: &Config) -> Arc<dyn ModelProvider> {
    Arc::new(ScriptedProvider::new(
        ModelIdentity::new(
            &config.expect_conversation_model().provider,
            "scripted",
            &config.expect_conversation_model().model,
        ),
        Vec::new(),
    ))
}

/// A provider whose every request waits until its run is cancelled, so a
/// turn on it can only end cancelled.
pub(in crate::app) struct HangUntilCancel;

impl ModelProvider for HangUntilCancel {
    fn identity(&self) -> ModelIdentity {
        ModelIdentity::new("test", "test", "model")
    }

    fn send_turn<'a>(&'a self, request: ModelRequest<'a>) -> ProviderFuture<'a> {
        Box::pin(async move {
            request.cancellation.cancelled().await;
            Err(rho_sdk::ProviderError::interrupted("cancelled"))
        })
    }
}

/// A tool-less session `id` on `config`'s model, whose provider has no
/// scripted turns.
pub(super) async fn idle_built(config: &Config, id: rho_sdk::SessionId) -> BuiltSession {
    built_on(config, id, idle_provider(config)).await
}

/// A tool-less session `id` on `provider`.
pub(super) async fn built_on(
    config: &Config,
    id: rho_sdk::SessionId,
    provider: Arc<dyn ModelProvider>,
) -> BuiltSession {
    let runtime = rho_sdk::Rho::builder()
        .provider_shared(Arc::clone(&provider))
        .build()
        .expect("test runtime");
    built_with(config, id, runtime, provider).await
}

/// A session `id` on the SDK `runtime`, built on `provider` with whatever
/// tools and hooks the test gave it, and no host tools of its own.
pub(super) async fn built_with(
    config: &Config,
    id: rho_sdk::SessionId,
    runtime: rho_sdk::Rho,
    provider: Arc<dyn ModelProvider>,
) -> BuiltSession {
    let session = runtime
        .session(SessionOptions::new().id(id))
        .await
        .expect("test session");
    BuiltSession {
        runtime,
        session,
        provider,
        tools: AppToolSet::disabled(),
        hooks: None,
        approval_receiver: None,
        prompt_template: None,
        prompt: Default::default(),
        diagnostics: RuntimeDiagnostics::new(config),
        tool_sources: None,
        provider_credentials: crate::app::session_assembly::ProviderCredentials::Found,
    }
}

/// A runtime around an [`idle_built`] session, saved in a new file under
/// `root`, which is also its workspace.
pub(super) async fn idle_runtime(root: &Path, config: &Config) -> SessionRuntime {
    runtime_on(root, config, idle_provider(config)).await
}

/// A runtime around a [`built_on`] session on `provider`, saved in a new
/// file under `root`, which is also its workspace.
pub(super) async fn runtime_on(
    root: &Path,
    config: &Config,
    provider: Arc<dyn ModelProvider>,
) -> SessionRuntime {
    let stored = StoredSession::create_in_root(root, root).expect("test session file");
    let id = rho_sdk::SessionId::from_string(stored.id()).expect("stored ids are session ids");
    let built = built_on(config, id, provider).await;
    SessionRuntime::for_tests(built, SessionStorage::saved(stored), config)
}

/// A runtime around a [`built_with`] session on the SDK `runtime`, saved in
/// a new file under `root`, which is also its workspace, for a host nobody
/// watches that offers `questions`.
pub(in crate::app) async fn unattended_runtime_on(
    root: &Path,
    config: &Config,
    questions: QuestionSupport,
    runtime: rho_sdk::Rho,
    provider: Arc<dyn ModelProvider>,
) -> SessionRuntime {
    let host = HostCapabilities {
        surfaces: None,
        pull_requests: None,
        browser: None,
        questions,
        ..HostCapabilities::unattended(UnattendedApprovals::Alone)
    };
    saved_runtime_on(root, config, host, runtime, provider, |_| None).await
}

/// [`unattended_runtime_on`] for a host that runs the session's children
/// as its own threads, and so wakes the idle session itself, as T3 Code
/// does.
pub(in crate::app) async fn host_woken_runtime_on(
    root: &Path,
    config: &Config,
    runtime: rho_sdk::Rho,
    provider: Arc<dyn ModelProvider>,
) -> SessionRuntime {
    let host = HostCapabilities {
        surfaces: None,
        pull_requests: None,
        browser: None,
        children: ChildAgents::HostThreads,
        ..HostCapabilities::unattended(UnattendedApprovals::Alone)
    };
    saved_runtime_on(root, config, host, runtime, provider, |_| None).await
}

/// [`unattended_runtime_on`] for a client that asked the daemon to start a
/// turn when the idle session's background work finishes, as
/// `idle_wake: turn` does. Its tools hold the pull request inbox
/// `pull_requests` gives for its id, and its host an inbox for notices of
/// the sessions it starts, as a daemon session's do.
pub(in crate::app) async fn idle_woken_runtime_on(
    root: &Path,
    config: &Config,
    runtime: rho_sdk::Rho,
    provider: Arc<dyn ModelProvider>,
    pull_requests: impl FnOnce(&rho_sdk::SessionId) -> Option<PullRequestInbox>,
) -> SessionRuntime {
    let host = HostCapabilities {
        surfaces: None,
        pull_requests: None,
        browser: None,
        peer_sessions: Some(crate::app::peer_sessions::PeerInbox::default()),
        starter_report: None,
        idle_turns: super::IdleTurns::Host,
        ..HostCapabilities::unattended(UnattendedApprovals::Alone)
    };
    saved_runtime_on(root, config, host, runtime, provider, pull_requests).await
}

/// [`idle_woken_runtime_on`] for a session that reports to a starter, as
/// session control starts one as such an agent, which asks its own
/// questions without waiting and takes their answers in turns the daemon
/// starts.
pub(in crate::app) async fn reporting_runtime_on(
    root: &Path,
    config: &Config,
    runtime: rho_sdk::Rho,
    provider: Arc<dyn ModelProvider>,
) -> SessionRuntime {
    let host = HostCapabilities {
        surfaces: None,
        pull_requests: None,
        browser: None,
        peer_sessions: Some(crate::app::peer_sessions::PeerInbox::default()),
        starter_report: Some(crate::app::starter_report::StarterReport::to(
            rho_sdk::SessionId::new(),
        )),
        idle_turns: super::IdleTurns::Host,
        ..HostCapabilities::unattended(UnattendedApprovals::Alone)
    };
    saved_runtime_on(root, config, host, runtime, provider, |_| None).await
}

/// A runtime around a [`built_with`] session on the SDK `runtime`, saved in
/// a new file under `root`, which is also its workspace, for `host`, its
/// tools holding the inbox `pull_requests` gives for its id, if any.
async fn saved_runtime_on(
    root: &Path,
    config: &Config,
    host: HostCapabilities,
    runtime: rho_sdk::Rho,
    provider: Arc<dyn ModelProvider>,
    pull_requests: impl FnOnce(&rho_sdk::SessionId) -> Option<PullRequestInbox>,
) -> SessionRuntime {
    let stored = StoredSession::create_in_root(root, root).expect("test session file");
    let id = rho_sdk::SessionId::from_string(stored.id()).expect("stored ids are session ids");
    let inbox = pull_requests(&id);
    let mut built = built_with(config, id, runtime, provider).await;
    if let Some(inbox) = inbox {
        built.tools.set_pull_requests_for_tests(inbox);
    }
    let mut build = test_build(config, root);
    build.host = host;
    SessionRuntime::for_tests_with(build, built, SessionStorage::saved(stored), config)
}

/// A runtime around a [`built_with`] session on the SDK `runtime`, whose
/// file under `root`, also its workspace, is created on its first save, as
/// a new daemon session's is, for a host nobody watches.
pub(in crate::app) async fn unsaved_unattended_runtime_on(
    root: &Path,
    config: &Config,
    runtime: rho_sdk::Rho,
    provider: Arc<dyn ModelProvider>,
) -> SessionRuntime {
    let id = rho_sdk::SessionId::new();
    let built = built_with(config, id.clone(), runtime, provider).await;
    let mut build = test_build(config, root);
    build.host = HostCapabilities::unattended(UnattendedApprovals::Alone);
    let (file_root, id) = (root.to_path_buf(), id.to_string());
    let storage = SessionStorage::unsaved(
        root.to_path_buf(),
        Box::new(move || {
            StoredSession::create_with_id_in_root_for_test(&file_root, &file_root, &id)
        }),
    );
    SessionRuntime::for_tests_with(build, built, storage, config)
}

/// How a test session is built: as a [`root_agent`] whose host answers its
/// approvals, configured from `workspace_root`.
pub(in crate::app) fn test_build(config: &Config, workspace_root: &Path) -> SessionBuild {
    SessionBuild {
        launch: SessionLaunch {
            config_path: workspace_root.join("rho-test-config.toml"),
            left_out: LeftOut::default(),
            diagnostics: RuntimeDiagnostics::new(config),
            agent: root_agent(config),
            prompt_suffix: None,
            host_prompt: None,
        },
        host: HostCapabilities {
            surfaces: None,
            pull_requests: None,
            browser: None,
            peer_sessions: None,
            starter_report: None,
            questions: QuestionSupport::Unavailable,
            secret_asks: crate::tools::mcp::McpSecretAsks::Unavailable,
            children: ChildAgents::InProcess,
            idle_turns: super::IdleTurns::Never,
            subagent_pool: crate::app::subagent_pool::SubagentPool::Own,
            environment: Default::default(),
            mcp_authorization: McpAuthorizationMode::NonInteractive,
            approvals: ApprovalPolicy::Host,
            parent_notices: None,
            session_use: super::SessionUse::Run(crate::app::session_assembly::SignIn::Required),
            tool_sources: crate::app::tools_prompt::ToolSourceLoad::Inline,
            cache_warming: crate::app::session_runtime::CacheWarming::None,
            model_requests: None,
        },
        run: RunShape {
            role: SessionRole::Daemon,
            max_steps: None,
            hook_labels: Default::default(),
        },
    }
}

impl SessionRuntime {
    /// A runtime around `built`, saved through `storage`, made as
    /// [`test_build`] says with the storage's workspace.
    pub(super) fn for_tests(built: BuiltSession, storage: SessionStorage, config: &Config) -> Self {
        let build = test_build(config, storage.cwd());
        Self::for_tests_with(build, built, storage, config)
    }

    /// A runtime around `built`, saved through `storage`, made as `build`
    /// says from the start, in `config`'s mode with the storage's
    /// workspace.
    pub(super) fn for_tests_with(
        build: SessionBuild,
        built: BuiltSession,
        storage: SessionStorage,
        config: &Config,
    ) -> Self {
        let workspace_root = storage.cwd().to_path_buf();
        Self::from_built_for_tests(
            build,
            built,
            storage,
            SessionPermission {
                mode: config.permission_mode,
                writes: Default::default(),
                workspace_root,
            },
            config.expect_conversation_model().auth.clone(),
            config.providers.clone(),
        )
    }

    /// A runtime around `built`, saved through `storage`, running as
    /// `build`'s launch agent with `permission`, `auth` and `providers`, for host
    /// fixtures that script their own session. It has none of a host's MCP
    /// servers or roots.
    pub(in crate::app) fn from_built_for_tests(
        build: SessionBuild,
        built: BuiltSession,
        storage: SessionStorage,
        permission: SessionPermission,
        auth: String,
        providers: crate::config::ProviderConfigs,
    ) -> Self {
        let agent = build.launch.agent.clone();
        Self::new(OpenedSession {
            build,
            built,
            storage,
            agent,
            auth,
            auth_origin: Default::default(),
            host_mcp: Default::default(),
            added_dirs: Default::default(),
            permission,
            reopen_notice: None,
            credentials: SessionCredentials::Scripted,
            providers,
        })
    }

    /// The session's live history, for host tests that compare it with what
    /// was saved.
    pub(in crate::app) fn history_for_tests(&self) -> Vec<rho_sdk::model::Message> {
        self.built.session.history()
    }

    /// Whether the session keeps its settings with its file rather than
    /// following the config, as it does from its first settings change on.
    pub(in crate::app) fn keeps_settings_for_tests(&self) -> bool {
        matches!(self.settings, super::saved_settings::SettingsPolicy::Keep)
    }

    /// Saves `record` as the session's choice for the sessions it starts,
    /// as a rho that wrote it would, then takes back what its file keeps,
    /// as a reopen does.
    pub(in crate::app) fn reopen_with_started_sessions_record_for_tests(&mut self, record: &str) {
        self.built.session.advance_revision().unwrap();
        let snapshot = self
            .durable_snapshot()
            .with_metadata(STARTED_SESSION_DEFAULTS_METADATA, record);
        let stored = self.storage.file().expect("a saved session");
        stored.save_snapshot(&snapshot, &[]).unwrap();
        let saved = StartedSessions::saved_in(stored);
        self.restore_started_session_defaults(saved);
    }

    /// The session's choice for the sessions it starts as its file keeps
    /// it, byte for byte.
    pub(in crate::app) fn saved_started_sessions_record_for_tests(&self) -> Option<String> {
        self.storage
            .file()
            .expect("a saved session")
            .session_metadata(STARTED_SESSION_DEFAULTS_METADATA)
            .unwrap()
    }
}