rho-coding-agent 2.25.0

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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use std::{collections::BTreeSet, future::Future, path::Path, pin::Pin, sync::Arc};

use agent_client_protocol::{
    schema::v1::{
        RequestPermissionRequest, RequestPermissionResponse, SessionId, SessionNotification,
        SessionUpdate, StopReason,
    },
    Error as AcpError,
};
use pretty_assertions::assert_eq;
use rho_providers::reasoning::ReasoningLevel;
use rho_sdk::{
    model::{ContentBlock, Message, ModelIdentity, ModelResponse},
    provider::{ModelProvider, ScriptedProvider, ScriptedTurn},
    SessionOptions, UserInput,
};

use super::*;
use crate::{
    agent::{
        AgentCapabilities, AgentCatalogSources, AgentId, ModelPolicy, PromptPolicy, ToolCapability,
        ToolPolicy,
    },
    app::{acp::session_host::mode::SessionPermission, session_assembly::BuiltSession},
    diagnostics::RuntimeDiagnostics,
    herdr::HerdrReporter,
    permission::PermissionMode,
    session::Session as StoredSession,
    tools::sdk_registry::{AppToolSet, ToolSetOptions},
};

struct NullPort;

impl AcpClientPort for NullPort {
    fn send_session_notification(
        &self,
        _notification: SessionNotification,
    ) -> Pin<Box<dyn Future<Output = Result<(), AcpError>> + Send + '_>> {
        Box::pin(async { Ok(()) })
    }

    fn request_permission(
        &self,
        _request: RequestPermissionRequest,
    ) -> Pin<Box<dyn Future<Output = Result<RequestPermissionResponse, AcpError>> + Send + '_>>
    {
        Box::pin(async { Err(AcpError::method_not_found()) })
    }
}

/// Read the durable state when the host can first observe the child selection,
/// before its first turn has written any checkpoints. A restart sees this file.
struct LaunchPort {
    stored: StoredSession,
    expected_override: Option<serde_json::Value>,
}

impl AcpClientPort for LaunchPort {
    fn send_session_notification(
        &self,
        notification: SessionNotification,
    ) -> Pin<Box<dyn Future<Output = Result<(), AcpError>> + Send + '_>> {
        Box::pin(async move {
            if matches!(notification.update, SessionUpdate::ConfigOptionUpdate(_)) {
                let saved = self
                    .stored
                    .session_metadata(MODEL_OVERRIDE_METADATA)
                    .unwrap()
                    .map(|encoded| serde_json::from_str::<serde_json::Value>(&encoded).unwrap());
                assert_eq!(saved, self.expected_override);
            }
            Ok(())
        })
    }

    fn request_permission(
        &self,
        request: RequestPermissionRequest,
    ) -> Pin<Box<dyn Future<Output = Result<RequestPermissionResponse, AcpError>> + Send + '_>>
    {
        NullPort.request_permission(request)
    }
}

fn definition(tools: ToolPolicy) -> AgentDefinition {
    AgentDefinition {
        id: AgentId::new("acp-child").unwrap(),
        description: "ACP child".into(),
        prompt: PromptPolicy::Extend("Inspect the requested files".into()),
        runtime: AgentRuntimeSpec::Rho {
            tools,
            model: ModelPolicy::Inherit,
            reasoning: None,
        },
    }
}

fn startup(cwd: &Path) -> AcpStartup {
    let config = Config {
        provider: "test".into(),
        model: "launch-model".into(),
        permission_mode: PermissionMode::Bypass,
        ..Config::default()
    };
    let agent = AgentBinder::bind(
        Arc::new(definition(ToolPolicy::All)),
        AgentInvocation {
            role: AgentRole::AutomationRoot,
            available_tools: AgentCapabilities::all_host_tools(),
        },
        &config,
    )
    .unwrap();
    AcpStartup {
        host: crate::app::acp::AcpHost::Generic,
        diagnostics: RuntimeDiagnostics::new(&config),
        config,
        config_path: cwd.join("config.toml"),
        cwd: cwd.to_path_buf(),
        no_system_prompt: false,
        no_tools: false,
        no_subagents: false,
        agent,
        herdr: HerdrReporter::default(),
        added_dirs: Default::default(),
    }
}

async fn scripted_built(
    config: &Config,
    id: rho_sdk::SessionId,
    tools: AppToolSet,
) -> BuiltSession {
    let provider: Arc<dyn ModelProvider> = Arc::new(ScriptedProvider::new(
        ModelIdentity::new(&config.provider, "scripted", &config.model),
        vec![ScriptedTurn::completed(ModelResponse::Assistant(vec![
            ContentBlock::Text("done".into()),
        ]))],
    ));
    let mut builder = rho_sdk::Rho::builder()
        .provider_shared(Arc::clone(&provider))
        .system_prompt(rho_sdk::SystemPrompt::Custom("test instructions".into()));
    for tool in tools.tools() {
        builder = builder.tool_shared(Arc::clone(tool));
    }
    let runtime = builder.build().unwrap();
    let session = runtime.session(SessionOptions::new().id(id)).await.unwrap();
    BuiltSession {
        runtime,
        session,
        provider,
        tools,
        hooks: None,
        approval_receiver: None,
        prompt_template: None,
        prompt: Default::default(),
        diagnostics: RuntimeDiagnostics::new(config),
    }
}

async fn host(cwd: &Path, startup: &AcpStartup) -> SessionHost {
    let stored = StoredSession::create_in_root(cwd, cwd).unwrap();
    let config = Config {
        model: "host-selected-model".into(),
        ..startup.config.clone()
    };
    let built = scripted_built(
        &config,
        rho_sdk::SessionId::from_string(stored.id()).unwrap(),
        AppToolSet::disabled(),
    )
    .await;
    SessionHost::from_built(
        SessionId::new(stored.id()),
        built,
        super::super::persist::HostStorage::saved(stored),
        Default::default(),
        SessionPermission {
            mode: PermissionMode::Supervised,
            writes: Default::default(),
            workspace_root: cwd.to_path_buf(),
        },
        startup,
        Vec::new(),
    )
}

// Covers: a child must bind its allowlist and delegated role before its first
// turn, preserving the host's pre-prompt mode, reasoning and session id. A call
// override must be durable before advertising the child, then survive the first
// checkpoint and reload without changing identity.
// Owner: ACP session rebind transaction (scripted provider, no credentials).
#[tokio::test]
async fn rebind_applies_child_tools_and_current_host_selection() {
    let cwd = tempfile::tempdir().unwrap();
    let startup = startup(cwd.path());
    let catalog = || {
        Ok(AgentCatalog::from_sources(AgentCatalogSources {
            rho_home: vec![crate::agent::AgentSource::read(
                "acp-child.md".into(),
                "---\ndescription: ACP child\ntools: [read_file, agent, agents, advisor]\n---\nInspect the requested files".into(),
            )],
            ..Default::default()
        })?)
    };
    for model_override in [None, Some("@review")] {
        let mut host = host(cwd.path(), &startup).await;
        let id = host.built.session.id().clone();
        let child = catalog()
            .unwrap()
            .find("acp-child")
            .unwrap()
            .definition
            .clone();
        let fingerprint = child.fingerprint();
        let expected_model = if model_override.is_some() {
            "call-model"
        } else {
            "host-selected-model"
        };
        let port = LaunchPort {
            stored: host.storage.file().unwrap().clone(),
            expected_override: model_override.map(|_| {
                serde_json::json!({
                    "provider": "test-override",
                    "model": "call-model",
                    "auth": "test-auth",
                })
            }),
        };
        // T3 picks a thought level before the child's first prompt; the rebind
        // must keep it because the definition sets none.
        host.built
            .session
            .set_reasoning_level(ReasoningLevel::High)
            .unwrap();
        let display = UserInput::text("/agent:acp-child inspect the parser");
        let response = host
            .run_as_agent_with(
                &display,
                AgentTask {
                    agent_id: child.id.to_string(),
                    model_override: model_override.map(str::to_owned),
                    input: UserInput::text("inspect the parser"),
                },
                &startup,
                &port,
                |base| {
                    // Catalog/credential resolution is the binder's own test gate.
                    // Inject its resolved selection here to exercise ACP persistence.
                    let mut base = base.clone();
                    if model_override.is_some() {
                        base.provider = "test-override".into();
                        base.model = "call-model".into();
                        base.auth = "test-auth".into();
                    }
                    bind_delegated_agent(child, /*model_override*/ None, &startup, &base)
                },
                async |agent, config, id| {
                    assert_eq!(config.reasoning, ReasoningLevel::High);
                    assert_eq!(config.model, expected_model);
                    assert_eq!(agent.fingerprint(), fingerprint);
                    let tools = AppToolSet::new(
                        &config,
                        RuntimeDiagnostics::new(&config),
                        ToolSetOptions::new(agent.rho_capabilities().unwrap().clone()),
                    );
                    Ok(SessionAssembly {
                        built: scripted_built(&config, id, tools).await,
                        workspace_root: cwd.path().to_path_buf(),
                        session_writes: Default::default(),
                    })
                },
            )
            .await
            .unwrap();
        let inventory: BTreeSet<_> = host
            .built
            .tools
            .tools()
            .iter()
            .map(|tool| tool.spec().name)
            .collect();
        assert_eq!(
            inventory,
            BTreeSet::from(["codemode".into(), "read_file".into(), "tool_search".into()])
        );
        assert_eq!(response.stop_reason, StopReason::EndTurn);
        assert_eq!(host.built.session.id(), &id);
        assert_eq!(host.current_model().model, expected_model);
        assert_eq!(host.permission.mode, PermissionMode::Supervised);
        let child_identity = host
            .storage
            .file()
            .unwrap()
            .stored_agent_identity()
            .unwrap()
            .unwrap();
        assert_eq!(
            child_identity,
            ("acp-child".into(), host.agent.fingerprint().to_string())
        );
        if model_override.is_some() {
            let stored = host.storage.file().unwrap();
            for rebound_auth in ["test-auth", "fallback-auth"] {
                let result = loaded_agent_with(
                    &startup,
                    stored,
                    startup.config.clone(),
                    catalog,
                    |definition, selection, startup, base| {
                        assert_eq!(
                            selection,
                            Some(ModelOverride::Saved {
                                provider: "test-override",
                                model: "call-model",
                                auth: "test-auth",
                            }),
                        );
                        assert_eq!(definition.fingerprint(), fingerprint);
                        let base = Config {
                            provider: "test-override".into(),
                            model: "call-model".into(),
                            auth: rebound_auth.into(),
                            ..base.clone()
                        };
                        bind_delegated_agent(
                            definition, /*model_override*/ None, startup, &base,
                        )
                    },
                );
                if rebound_auth != "test-auth" {
                    assert!(
                        result.is_err(),
                        "resume must not substitute another auth profile"
                    );
                    continue;
                }
                let (loaded, config) = result.unwrap();
                assert_eq!(loaded.fingerprint(), fingerprint);
                assert_eq!(loaded.rho_capabilities(), host.agent.rho_capabilities());
                assert_eq!(config.model, expected_model);
            }
        } else {
            assert_eq!(
                host.storage
                    .file()
                    .unwrap()
                    .session_metadata(MODEL_OVERRIDE_METADATA)
                    .unwrap(),
                None
            );
        }
        host.shutdown().await;
    }
}

// Covers: rebinding must not silently discard a conversation, including a
// loaded conversation whose completed-runs counter starts at zero.
// Owner: ACP session rebind transaction.
#[tokio::test]
async fn rebind_rejects_nonfresh_sessions_without_replacing_them() {
    let cwd = tempfile::tempdir().unwrap();
    let startup = startup(cwd.path());
    for (completed_runs, history) in [
        (0, vec![Message::user_text("retained conversation")]),
        (1, Vec::new()),
    ] {
        let mut host = host(cwd.path(), &startup).await;
        host.completed_runs = completed_runs;
        for message in history {
            host.built.session.append_message(message).unwrap();
        }
        let before = host.built.session.snapshot();
        let input = UserInput::text("task");
        let error = host
            .run_as_agent_with(
                &input,
                AgentTask {
                    agent_id: "acp-child".into(),
                    model_override: None,
                    input: input.clone(),
                },
                &startup,
                &NullPort,
                |_| panic!("nonfresh sessions must not rebind"),
                |_, _, _| async { panic!("nonfresh sessions must not rebuild") },
            )
            .await
            .unwrap_err();
        assert!(error.downcast_ref::<CommandRejected>().is_some());
        assert_eq!(host.built.session.snapshot(), before);
        host.shutdown().await;
    }
}

// Covers: a reloaded child must come back with its delegated tool boundary,
// never the root's, even when it shares the launch agent's id; a root session
// stays the launch agent; a changed definition fails the load.
// Owner: ACP session load agent selection.
#[test]
fn load_restores_the_child_binding_or_fails() {
    let cwd = tempfile::tempdir().unwrap();
    let agents = cwd.path().join(".agents/agents");
    std::fs::create_dir_all(&agents).unwrap();
    let startup = startup(cwd.path());
    // Same id as the launch agent, so only the persisted role tells them apart.
    let file = agents.join(format!("{}.md", startup.agent.id()));
    std::fs::write(
        &file,
        "---\ndescription: Loaded child\ntools: [read_file, agent]\n---\nInspect files\n",
    )
    .unwrap();
    let catalog = || {
        Ok(AgentCatalog::discover_with_home(
            cwd.path(),
            /*home*/ None,
        )?)
    };
    let definitions = catalog().unwrap();
    let definition = &definitions
        .find(startup.agent.id().as_str())
        .unwrap()
        .definition;
    let session = |root: &Path| {
        StoredSession::create_in_root_with_agent(
            root,
            cwd.path(),
            startup.agent.id().as_str(),
            &startup.agent.fingerprint().to_string(),
        )
        .unwrap()
    };
    let child_root = tempfile::tempdir().unwrap();
    let child = session(child_root.path());
    child
        .rebind_fresh_delegated_agent(
            startup.agent.id().as_str(),
            &definition.fingerprint().to_string(),
            /*initial_snapshot*/ None,
        )
        .unwrap();

    let (agent, _) = loaded_agent(&startup, &child, startup.config.clone(), catalog).unwrap();
    assert_eq!(agent.fingerprint(), definition.fingerprint());
    assert_eq!(
        agent.rho_capabilities(),
        Some(&AgentCapabilities::new([ToolCapability::ReadFile].into()))
    );

    let root_dir = tempfile::tempdir().unwrap();
    let root = session(root_dir.path());
    let (agent, _) = loaded_agent(&startup, &root, startup.config.clone(), catalog).unwrap();
    assert_eq!(agent.fingerprint(), startup.agent.fingerprint());

    std::fs::write(
        &file,
        "---\ndescription: Loaded child\ntools: [read_file, write_file]\n---\nInspect files\n",
    )
    .unwrap();
    let snapshot = child
        .snapshot_for_resume(
            ModelIdentity::new("test", "test", "call-model"),
            "cache".into(),
        )
        .unwrap()
        .with_metadata(
            MODEL_OVERRIDE_METADATA,
            r#"{"provider":"test","model":"call-model","auth":"test-auth"}"#,
        );
    child.save_snapshot(&snapshot, &[]).unwrap();
    assert!(loaded_agent_with(
        &startup,
        &child,
        startup.config.clone(),
        catalog,
        |_, _, _, _| panic!("changed definitions must fail before override binding"),
    )
    .is_err());
}