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
420
421
422
423
424
425
426
427
428
429
use std::{num::NonZeroUsize, sync::Mutex};

use pretty_assertions::assert_eq;
use rho_sdk::{tool::tool_progress_channel, CancellationToken};

use super::*;
use crate::{
    agent::AgentCatalogSources,
    tools::{mcp::exported_name::namespaced_tool_name, sdk_registry::StaticToolBundle},
};

type RecordedCalls = Arc<Mutex<Vec<(String, ToolCallId, Value)>>>;

struct RecordingTool {
    name: String,
    calls: RecordedCalls,
    result: Result<ToolOutput, ToolError>,
}

impl Tool for RecordingTool {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: self.name.clone(),
            description: String::new(),
            input_schema: json!({"type": "object"}),
        }
    }

    fn call<'a>(&'a self, invocation: ToolInvocation, _context: ToolContext) -> ToolFuture<'a> {
        self.calls.lock().unwrap().push((
            self.name.clone(),
            invocation.id().clone(),
            invocation.into_arguments(),
        ));
        Box::pin(std::future::ready(self.result.clone()))
    }
}

fn invocation(arguments: Value) -> ToolInvocation {
    ToolInvocation::new(ToolCallId::from_string("host-call").unwrap(), arguments)
}

fn context() -> ToolContext {
    let (progress, _receiver) = tool_progress_channel(NonZeroUsize::MIN);
    ToolContext::new(/*workspace*/ None, CancellationToken::new(), progress)
}

fn catalog() -> AgentCatalog {
    AgentCatalog::from_sources(AgentCatalogSources {
        rho_home: vec![
            crate::agent::AgentSource::read(PathBuf::from("host-worker.md"), "---\ndescription: host implementation\n---\nUse this child policy".into()),
            crate::agent::AgentSource::read(PathBuf::from("external-worker.md"), "---\ndescription: external implementation\nruntime: claude-cli\ntools: [Read]\n---\nUse the external runtime".into()),
        ],
        ..Default::default()
    }).unwrap()
}

struct Fixture {
    orchestrator: Arc<HostOrchestrator>,
    calls: RecordedCalls,
    catalog: AgentCatalog,
}

impl Fixture {
    fn new(delegate_result: Result<ToolOutput, ToolError>) -> Self {
        Self::with_capabilities(delegate_result, /*capabilities*/ None)
    }

    /// `capabilities` is T3's optional `orchestrator_capabilities` tool.
    fn with_capabilities(
        delegate_result: Result<ToolOutput, ToolError>,
        capabilities: Option<Result<ToolOutput, ToolError>>,
    ) -> Self {
        let calls = RecordedCalls::default();
        let mut tools = AppToolSet::disabled();
        tools.add_bundle(StaticToolBundle::new(
            [
                ("delegate_task", delegate_result),
                (
                    "task_status",
                    Ok(ToolOutput::text("host progress").with_structured_content(
                        json!({"status": "waiting", "hasPendingChildRuns": true}),
                    )),
                ),
                (
                    "task_cancel",
                    Ok(ToolOutput::text("host stopped").with_structured_content(
                        json!({"taskId": "task-1", "status": "cancel_requested"}),
                    )),
                ),
            ]
            .into_iter()
            .chain(capabilities.map(|result| ("orchestrator_capabilities", result)))
            .map(|(name, result)| {
                Arc::new(RecordingTool {
                    name: namespaced_tool_name("t3-code", name),
                    calls: calls.clone(),
                    result,
                }) as Arc<dyn Tool>
            })
            .collect(),
        ));
        Self {
            orchestrator: Arc::new(HostOrchestrator::connect(&tools)),
            calls,
            catalog: catalog(),
        }
    }

    fn agent_tool(&self) -> HostAgentTool {
        HostAgentTool::new(
            self.orchestrator.clone(),
            Path::new("."),
            crate::workspace::ProjectTrusts::UNTRUSTED,
            &self.catalog,
            rho_tools::DEFAULT_MAX_OUTPUT_BYTES,
            Arc::new(()),
        )
    }

    async fn launch(&self, agent_id: &str) -> Result<ToolOutput, ToolError> {
        self.launch_args(json!({"agent_id": agent_id, "prompt": "Implement the parser"}))
            .await
    }

    async fn launch_args(&self, arguments: Value) -> Result<ToolOutput, ToolError> {
        let args = parse_agent_args(arguments)?;
        self.agent_tool()
            .launch(
                invocation(json!({})).id().clone(),
                &self.catalog.find(&args.agent_id).unwrap().definition,
                &args,
                context(),
            )
            .await
    }
}

fn started_reply() -> ToolOutput {
    ToolOutput::text("host accepted").with_structured_content(json!({
        "taskId": "task-1", "childThreadId": "thread-1", "status": "running",
    }))
}

// Covers: a per-call model always reaches the child's rebind command; T3 is
// queried for a label target only for a `provider/model` reference; and the
// launch still succeeds (with the parent's label) when no safe target applies
// -- the capabilities tool is absent, the call fails, or the model is not
// offered. `asks_t3` and `target` are explicit per row, not derived.
// Owner: host agent launch forwarding, including parsed shared tool arguments.
#[tokio::test]
async fn model_override_reaches_the_child_command_and_an_offered_target() {
    const LUNA: &str = "openai-codex/gpt-6-luna";
    let prompt = "\nInspect the parser\n\n--model is literal task text\n";
    let offers_luna = || {
        Some(Ok(ToolOutput::text("capabilities")
            .with_structured_content(json!({
                "inheritedProviderInstanceId": "rho",
                "inheritedOptions": [{"id": "mode", "value": "plan"}],
                "providers": [{
                    "providerInstanceId": "rho",
                    "models": [{"id": LUNA, "options": [{"id": "mode", "values": ["plan"]}]}],
                }],
            }))))
    };
    let luna_target = json!({"model": LUNA, "options": [{"id": "mode", "value": "plan"}]});
    let failed = || Some(Err(ToolError::new(ToolErrorKind::Execution, "host down")));
    for (case, model, capabilities, asks_t3, target) in [
        (
            "no model override: no query, no target",
            None,
            None,
            false,
            None,
        ),
        (
            "alias: skipped before the query, no target",
            Some("@review"),
            offers_luna(),
            false,
            None,
        ),
        (
            "offered provider/model: query, target with the parent's options",
            Some(LUNA),
            offers_luna(),
            true,
            Some(luna_target),
        ),
        (
            "failed query: launch proceeds with the parent's label",
            Some(LUNA),
            failed(),
            true,
            None,
        ),
        (
            "no capabilities tool: no query, parent's label",
            Some(LUNA),
            None,
            false,
            None,
        ),
    ] {
        let fixture = Fixture::with_capabilities(Ok(started_reply()), capabilities);
        let mut arguments = json!({"agent_id": "host-worker", "prompt": prompt});
        if let Some(model) = model {
            arguments["model"] = json!(model);
        }
        let output = fixture.launch_args(arguments).await.unwrap();
        let task = match model {
            Some(model) => format!("/agent:host-worker --model {model} -- {prompt}"),
            None => format!("/agent:host-worker {prompt}"),
        };
        let mut delegated = json!({"task": task, "mode": "async"});
        if let Some(target) = target {
            delegated["target"] = target;
        }
        let call = |name, arguments| {
            (
                namespaced_tool_name("t3-code", name),
                invocation(json!({})).id().clone(),
                arguments,
            )
        };
        let mut expected = Vec::new();
        if asks_t3 {
            expected.push(call("orchestrator_capabilities", json!({"search": model})));
        }
        expected.push(call("delegate_task", delegated));
        assert_eq!(*fixture.calls.lock().unwrap(), expected, "{case}");
        assert_eq!(
            output.structured_content(),
            Some(
                &serde_json::to_value(
                    AgentRunView::started("task-1".into(), "host-worker".into(),)
                )
                .unwrap()
            ),
            "{case}",
        );
    }
}

// Covers: a cancel during the capabilities query must cancel the launch and
// never send delegate_task, so a cancelled turn cannot spawn an untracked
// child. Owner: host agent launch forwarding.
#[tokio::test]
async fn capabilities_cancellation_cancels_the_launch_before_delegating() {
    let fixture =
        Fixture::with_capabilities(Ok(started_reply()), Some(Err(ToolError::cancelled())));
    let error = fixture
        .launch_args(json!({
            "agent_id": "host-worker",
            "prompt": "Implement the parser",
            "model": "openai-codex/gpt-6-luna",
        }))
        .await
        .unwrap_err();
    assert_eq!(error.kind(), ToolErrorKind::Cancelled);
    assert_eq!(
        *fixture.calls.lock().unwrap(),
        vec![(
            namespaced_tool_name("t3-code", "orchestrator_capabilities"),
            invocation(json!({})).id().clone(),
            json!({"search": "openai-codex/gpt-6-luna"}),
        )]
    );
    assert!(fixture.orchestrator.runs().is_empty());
}

// Covers: launch must keep the host task receipt, fail loud on a bad/missing
// receipt, and never register a phantom run. Owner: host delegation tools.
#[tokio::test]
async fn host_launch_records_only_successful_receipts() {
    let started =
        serde_json::to_value(AgentRunView::started("task-1".into(), "host-worker".into())).unwrap();
    for (reply, expected) in [
        (Ok(started_reply()), Ok(started)),
        (
            Ok(ToolOutput::text("missing task")
                .with_structured_content(json!({"childThreadId": "thread-1"}))),
            Err(ToolErrorKind::Execution),
        ),
        (
            Ok(ToolOutput::text("host rejected").failed()),
            Err(ToolErrorKind::Execution),
        ),
        (
            Err(ToolError::new(ToolErrorKind::PolicyDenied, "host rejected")),
            Err(ToolErrorKind::Execution),
        ),
        (Err(ToolError::cancelled()), Err(ToolErrorKind::Cancelled)),
    ] {
        let fixture = Fixture::new(reply);
        let result = fixture.launch("host-worker").await;
        let successful = result.is_ok();
        assert_eq!(
            result
                .map(|output| output.structured_content().cloned().unwrap())
                .map_err(|error| error.kind()),
            expected
        );
        assert_eq!(fixture.calls.lock().unwrap().len(), 1);
        let runs = fixture.orchestrator.runs();
        let views = runs.iter().map(HostRunView::from).collect::<Vec<_>>();
        assert_eq!(
            serde_json::to_value(views).unwrap(),
            if successful {
                json!([{"task_id": "task-1", "child_thread_id": "thread-1", "agent_id": "host-worker", "title": "Implement the parser"}])
            } else {
                json!([])
            }
        );
    }
}

// Covers: stop must reach T3 with its reason, status must keep T3's opaque
// lifecycle facts, and unsupported messaging must not call MCP. Owner: host tools.
#[tokio::test]
async fn management_forwards_host_operations_without_native_state_mapping() {
    let fixture = Fixture::new(Ok(started_reply()));
    fixture.launch("host-worker").await.unwrap();
    fixture.calls.lock().unwrap().clear();
    let tool = HostAgentsTool {
        orchestrator: fixture.orchestrator.clone(),
        max_output_bytes: rho_tools::DEFAULT_MAX_OUTPUT_BYTES,
    };
    for (arguments, expected, remote) in [
        (
            json!({"action": "status", "id": "task-1"}),
            Ok(
                json!({"action": "status", "task_id": "task-1", "host": {"status": "waiting", "hasPendingChildRuns": true}}),
            ),
            Some(("task_status", json!({"taskId": "task-1"}))),
        ),
        (
            json!({"action": "status", "id": "task-from-reloaded-session"}),
            Ok(
                json!({"action": "status", "task_id": "task-from-reloaded-session", "host": {"status": "waiting", "hasPendingChildRuns": true}}),
            ),
            Some((
                "task_status",
                json!({"taskId": "task-from-reloaded-session"}),
            )),
        ),
        (
            json!({"action": "stop", "id": "task-1", "reason": "task superseded"}),
            Ok(
                json!({"action": "stop", "task_id": "task-1", "host": {"taskId": "task-1", "status": "cancel_requested"}}),
            ),
            Some((
                "task_cancel",
                json!({"taskId": "task-1", "reason": "task superseded"}),
            )),
        ),
        (
            json!({"action": "message", "id": "task-1", "message": "new task"}),
            Err(ToolErrorKind::InvalidArguments),
            None,
        ),
    ] {
        fixture.calls.lock().unwrap().clear();
        let result = tool.call(invocation(arguments), context()).await;
        assert_eq!(
            result
                .map(|output| output.structured_content().cloned().unwrap())
                .map_err(|error| error.kind()),
            expected
        );
        let expected_calls = remote
            .into_iter()
            .map(|(name, args)| {
                (
                    namespaced_tool_name("t3-code", name),
                    invocation(json!({})).id().clone(),
                    args,
                )
            })
            .collect::<Vec<_>>();
        assert_eq!(*fixture.calls.lock().unwrap(), expected_calls);
    }
}

// Covers: host mode must not advertise or launch external-runtime definitions.
// Owner: host runtime policy; no environment-dependent catalog discovery needed.
#[tokio::test]
async fn external_runtime_is_not_advertised_or_launched() {
    let fixture = Fixture::new(Ok(started_reply()));
    let advertised = fixture.agent_tool().spec().input_schema["properties"]["agent_id"]["enum"]
        .as_array()
        .unwrap()
        .clone();
    assert_eq!(
        (
            advertised.contains(&json!("host-worker")),
            advertised.contains(&json!("external-worker"))
        ),
        (true, false),
        "{advertised:?}"
    );
    for model in [None, Some("@review")] {
        let error = fixture
            .launch_args(json!({
                "agent_id": "external-worker", "prompt": "inspect", "model": model,
            }))
            .await
            .unwrap_err();
        assert_eq!(error.kind(), ToolErrorKind::InvalidArguments);
    }
    assert_eq!(*fixture.calls.lock().unwrap(), Vec::new());
    assert!(fixture.orchestrator.runs().is_empty());
}

// Covers: under `--t3code`, a session without T3's task tools (such as T3's
// provider status probe) still starts, but launching a child fails loud instead
// of falling back to in-process subagents or recording a phantom run.
// Owner: host delegation tools.
#[tokio::test]
async fn launch_without_host_contract_fails_without_a_run() {
    let fixture = Fixture {
        orchestrator: Arc::new(HostOrchestrator::connect(&AppToolSet::disabled())),
        calls: RecordedCalls::default(),
        catalog: catalog(),
    };
    let error = fixture.launch("host-worker").await.unwrap_err();
    assert_eq!(error.kind(), ToolErrorKind::Execution);
    assert!(fixture.orchestrator.runs().is_empty());
}