rho-coding-agent 3.13.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
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
//! Supervise one ACP process and funnel every outcome through one terminal write.

use super::{
    adapters::{Adapter, ADAPTERS},
    driver::{self, DriverOutcome},
    policy::{AcpAgentPolicy, AcpProtocol},
    transport::child_transport,
    turn::TurnClassification,
    v2::{self, Driven},
    AcpSpawnPlan,
};
use crate::{
    cli_runtime::{
        agent_event::{render::EventRenderer, AgentEvent},
        parent_messages::{ParentMessage, ParentMessageInbox},
        read_log_tail,
        status_sink::StatusSink,
        stream_effect::TerminalResult,
        BeforeSpawn, CliExecutable, CliPrompt, CliSessionOverrides, OwnedChild,
    },
    run_artifacts::RunArtifactIdentity,
    session_environment::Ambient,
    subagent::RunStatus,
};
use rho_tools::cancellation::RunCancellation;
use std::{
    ops::ControlFlow,
    path::PathBuf,
    process::Stdio,
    sync::{Arc, Mutex},
};
use tokio::{
    process::{ChildStdin, ChildStdout},
    sync::watch,
};

/// Executor-facing inputs. ACP session ids are protocol metadata, not resume ids.
pub(crate) struct AcpSessionRequest {
    pub(crate) identity: RunArtifactIdentity,
    pub(crate) prompt: CliPrompt,
    pub(crate) output_file: PathBuf,
    pub(crate) cwd: PathBuf,
    pub(crate) cancellation: RunCancellation,
    pub(crate) status_tx: Option<watch::Sender<RunStatus>>,
    pub(crate) started_status: Option<RunStatus>,
    pub(crate) parent_messages: Option<ParentMessageInbox>,
    pub(crate) overrides: CliSessionOverrides,
    /// The environment the agent runs in and is found on: its session's when
    /// the run launched (#1659).
    pub(crate) environment: Ambient,
}

pub(super) fn open_sink<P: AcpAgentPolicy>(
    request: &mut AcpSessionRequest,
    policy: &P,
) -> anyhow::Result<StatusSink> {
    let mut sink = match request.started_status.take() {
        Some(status) => StatusSink::continue_from(
            request.output_file.clone(),
            status,
            &request.prompt,
            request.status_tx.take(),
            &request.overrides,
            policy.rate_limit_recorder(),
            policy.label(),
        ),
        None => StatusSink::new(
            request.output_file.clone(),
            &request.identity,
            &request.prompt,
            request.status_tx.take(),
            policy.rate_limit_recorder(),
            policy.label(),
        ),
    }?;
    if let Some(observer) = request.overrides.observer.take() {
        sink.observed_by(observer);
    }
    Ok(sink)
}

fn prepare<P: AcpAgentPolicy>(request: &AcpSessionRequest, policy: &mut P) -> Result<(), String> {
    let run_dir = request
        .output_file
        .parent()
        .ok_or("acp: result path has no run directory")?;
    policy.prepare(run_dir)
}

/// The run's first prompt as the agent gets it: the overrides' preamble,
/// which nothing records, then the prompt; and the background results it
/// carries ahead of that, as a content block of their own, which show once
/// it is sent. Takes the results from the overrides.
fn sent_prompt(request: &mut AcpSessionRequest) -> SentPrompt {
    let prompt = match &request.overrides.preamble {
        Some(preamble) => request.prompt.with_preamble(preamble),
        None => request.prompt.clone(),
    };
    SentPrompt {
        prompt,
        results: request.overrides.prompt_results.take(),
    }
}

/// The run's first prompt ([`sent_prompt`]). Its results stay here until a
/// prompt carries them, so an agent process that never prompted, as one
/// that answered v1 to v2, leaves them for the next.
struct SentPrompt {
    prompt: CliPrompt,
    results: Option<ParentMessage>,
}

pub(super) async fn run_child<P: AcpAgentPolicy>(
    request: &mut AcpSessionRequest,
    mut policy: P,
    renderer: &mut EventRenderer,
    sink: &mut StatusSink,
) -> Result<DriverOutcome, String> {
    if request.cancellation.is_cancelled() {
        return Ok(stopped());
    }
    prepare(request, &mut policy)?;
    let mut prompt = sent_prompt(request);
    // A frozen launch's executable is a handle whose path (`/proc/self/fd/N`)
    // names no adapter, so it has no place in the adapter cache.
    let (executable, cached) = match request.overrides.executable.take() {
        Some(executable) => (executable, false),
        None => (policy.resolve_executable(&request.environment)?, true),
    };
    let log_path = policy.log_path(&request.output_file);
    let asked = policy.protocol();
    // Shared with the connection after setup; callers keep no mutable
    // policy while the agent is running.
    let policy = Arc::new(Mutex::new(policy));
    let mut run = Run {
        request,
        prompt: &mut prompt,
        renderer,
        sink,
        adapter: cached.then(|| Adapter {
            cache: &ADAPTERS,
            path: executable.path(),
        }),
    };
    let mut protocol = start_on(asked, &mut run);
    loop {
        let driven = run_process(protocol, &policy, &mut run, &executable, &log_path).await?;
        match after_process(protocol, driven, &mut run) {
            ControlFlow::Break(outcome) => return outcome,
            ControlFlow::Continue(next) => protocol = next,
        }
    }
}

/// Runs one agent process on `protocol`, from spawn to terminate.
async fn run_process<P: AcpAgentPolicy>(
    protocol: AcpProtocol,
    policy: &Arc<Mutex<P>>,
    run: &mut Run<'_>,
    executable: &CliExecutable,
    log_path: &std::path::Path,
) -> Result<Driven, String> {
    let program = policy.lock().expect("ACP policy").label().program;
    let plan = policy.lock().expect("ACP policy").spawn_plan()?;
    let log = tokio::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(log_path)
        .await
        .map_err(|source| format!("{program}: could not open log file: {source}"))?
        .into_std()
        .await;
    let (mut child, stdin, stdout) = spawn_agent(
        program,
        executable,
        plan,
        log.into(),
        run.request.overrides.before_spawn.as_ref(),
        &run.request.environment,
    )?;
    let (outcome, exit) = {
        let driver = drive(
            protocol,
            child_transport(stdin, stdout, program),
            policy,
            run,
        );
        tokio::pin!(driver);
        // Observe leader exit alongside the protocol: a descendant can inherit
        // stdout, so EOF alone may never come. OwnedChild::wait kills the rest of
        // the group, which closes the pipe; the driver then drains what was already
        // sent (a buffered stop reason still wins) and reports the closed transport.
        tokio::select! {
            outcome = &mut driver => (outcome, None),
            status = child.wait() => (driver.await, Some(status)),
        }
    };
    if exit.is_none() {
        // An ACP agent need not exit on stdin EOF after a turn (a recorded one
        // never did within 10 s, 10/10 runs; see the commit that removed the
        // cursor runtime). Always terminate, even on success; OwnedChild gives
        // 200 ms then kills the tree.
        child.terminate().await;
    }
    let tail = read_log_tail(log_path).await;
    outcome.map_err(|source| {
        let source = match exit {
            Some(Ok(status)) => format!("{source} ({program} exited: {status})"),
            Some(Err(wait)) => format!("{source} ({program} wait failed: {wait})"),
            None => source,
        };
        if tail.is_empty() {
            source
        } else {
            format!("{source}: {tail}")
        }
    })
}

/// What each agent process of a run works from and writes to.
struct Run<'a> {
    request: &'a mut AcpSessionRequest,
    prompt: &'a mut SentPrompt,
    renderer: &'a mut EventRenderer,
    sink: &'a mut StatusSink,
    /// The agent's executable, in the process's adapter cache; `None` for
    /// a test's channel.
    adapter: Option<Adapter<'a>>,
}

/// What the run does once an agent process on `protocol` came to
/// `driven`: settle, or start another on the protocol it continues with. An
/// agent that answers v1 to v2 runs again, in a new process, on v1, unless
/// the run was cancelled meanwhile; the run says so, since it then runs
/// without what v2 adds. Nothing continues from v1, so a run starts at most
/// two processes.
fn after_process(
    protocol: AcpProtocol,
    driven: Driven,
    run: &mut Run<'_>,
) -> ControlFlow<Result<DriverOutcome, String>, AcpProtocol> {
    match (driven, protocol) {
        (Driven::Ran(outcome), _) => ControlFlow::Break(Ok(outcome)),
        (Driven::AgentSpeaksV1, AcpProtocol::V2) if run.request.cancellation.is_cancelled() => {
            ControlFlow::Break(Ok(stopped()))
        }
        (Driven::AgentSpeaksV1, AcpProtocol::V2) => {
            on_v1_notice(run);
            ControlFlow::Continue(AcpProtocol::V1)
        }
        (Driven::AgentSpeaksV1, AcpProtocol::V1) => {
            ControlFlow::Break(Err("acp: the agent answered v1 to v1".into()))
        }
    }
}

/// Says the run goes on v1, without what v2 adds.
fn on_v1_notice(run: &mut Run<'_>) {
    driver::render(
        run.renderer,
        run.sink,
        AgentEvent::Notice(
            "acp: the agent speaks ACP v1 only, so rho runs it on v1; a newer version of it may speak v2"
                .into(),
        ),
    );
}

/// The protocol a run starts on, its policy asking `asked`: v1 for an
/// agent its adapter cache knows to answer v1 to v2, so the run starts one
/// process, and says so as a fallback would.
fn start_on(asked: AcpProtocol, run: &mut Run<'_>) -> AcpProtocol {
    let protocol = run.adapter.map_or(asked, |adapter| adapter.start_on(asked));
    if protocol != asked {
        on_v1_notice(run);
    }
    protocol
}

/// Runs one connection to an agent process on `protocol`.
async fn drive<P: AcpAgentPolicy>(
    protocol: AcpProtocol,
    transport: impl agent_client_protocol::ConnectTo<agent_client_protocol::Client> + 'static,
    policy: &Arc<Mutex<P>>,
    run: &mut Run<'_>,
) -> Result<Driven, String> {
    let Run {
        request,
        prompt,
        renderer,
        sink,
        adapter,
    } = run;
    let tools = request.overrides.agent_tools.clone();
    let policy = Arc::clone(policy);
    let context = driver::DriverContext {
        prompt: &prompt.prompt,
        cwd: &request.cwd,
        resume: request.overrides.resume.as_deref(),
        cancellation: &request.cancellation,
        inbox: &mut request.parent_messages,
        renderer,
        sink,
        person: request.overrides.person.as_ref(),
        prompt_results: &mut prompt.results,
        background_work: request.overrides.background_work,
        runtime_children: request.overrides.runtime_children.clone(),
        adapter: *adapter,
    };
    match protocol {
        AcpProtocol::V1 => driver::run(transport, policy, context, tools)
            .await
            .map(Driven::Ran),
        AcpProtocol::V2 => v2::run(transport, policy, context, tools).await,
    }
}

/// Spawn the agent from its plan with piped protocol stdio, returning the
/// child and its taken stdin/stdout. `stderr` is where the agent's log goes.
/// The agent gets all of `environment`, credentials included, since it signs
/// in and runs commands itself, then the plan's overrides (#1659).
pub(super) fn spawn_agent(
    program: &str,
    executable: &CliExecutable,
    plan: AcpSpawnPlan,
    stderr: Stdio,
    before_spawn: Option<&BeforeSpawn>,
    environment: &Ambient,
) -> Result<(OwnedChild, ChildStdin, ChildStdout), String> {
    let AcpSpawnPlan { argv, cwd, env } = plan;
    let mut command = executable
        .try_command(&argv)
        .map_err(|source| format!("{program}: {source}"))?;
    environment.apply_full(&mut command);
    command
        .current_dir(cwd)
        .envs(env)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(stderr)
        .kill_on_drop(true);
    if let Some(before_spawn) = before_spawn {
        before_spawn(&mut command).map_err(|source| {
            format!("{program}: frozen executable changed before spawn: {source}")
        })?;
    }
    let mut child = OwnedChild::spawn(command).map_err(|source| {
        format!(
            "{program}: failed to spawn `{}`: {source}",
            executable.display()
        )
    })?;
    let stdin = child
        .stdin()
        .ok_or_else(|| format!("{program}: missing child stdin"))?;
    let stdout = child
        .stdout()
        .ok_or_else(|| format!("{program}: missing child stdout"))?;
    Ok((child, stdin, stdout))
}

fn stopped() -> DriverOutcome {
    DriverOutcome {
        classification: TurnClassification::Stopped,
        session_id: None,
        result_text: String::new(),
        turns: 0,
    }
}

/// Records what the run's end shows of its calls, however it ended
/// ([`EventRenderer::run_ended`]), before its end is settled.
pub(super) fn run_ended(renderer: &mut EventRenderer, sink: &mut StatusSink) {
    for effect in renderer.run_ended() {
        sink.apply_effect(effect);
    }
}

/// Every setup, transport, turn, or cancellation outcome reaches exactly one
/// terminal sink method. No driver branch writes a terminal artifact itself.
pub(super) async fn settle(mut sink: StatusSink, outcome: Result<DriverOutcome, String>) {
    let outcome = match outcome {
        Ok(outcome) => outcome,
        Err(error) => {
            sink.fail(error).await;
            return;
        }
    };
    let terminal = TerminalResult {
        result_text: outcome.result_text,
        session_id: outcome.session_id,
        turns: outcome.turns,
    };
    match (
        &outcome.classification,
        outcome.classification.failure_detail(),
    ) {
        (TurnClassification::Success, _) => sink.succeed(&terminal).await,
        (TurnClassification::Stopped, _) => sink.stop("cancelled", &terminal).await,
        (
            TurnClassification::Failure { .. }
            | TurnClassification::AgentFailed { .. }
            | TurnClassification::Invalid,
            detail,
        ) => {
            let detail = detail.expect("a failed turn has a detail");
            sink.fail_turn(&terminal, detail).await;
        }
    }
}

/// Same artifact boundary as production, replacing only the physical
/// transport: each agent process is a channel `connect` opens. `adapter`,
/// when set, is the agent's entry in an adapter cache, as an executable's.
#[cfg(test)]
pub(super) async fn run_on_channels<P: AcpAgentPolicy>(
    mut request: AcpSessionRequest,
    mut policy: P,
    adapter: Option<Adapter<'_>>,
    mut connect: impl FnMut() -> agent_client_protocol::Channel,
) -> anyhow::Result<()> {
    let mut sink = open_sink(&mut request, &policy)?;
    let mut renderer = EventRenderer::new(request.cwd.clone());
    let outcome = match prepare(&request, &mut policy) {
        Ok(()) => {
            let mut prompt = sent_prompt(&mut request);
            let asked = policy.protocol();
            let policy = Arc::new(Mutex::new(policy));
            let mut run = Run {
                request: &mut request,
                prompt: &mut prompt,
                renderer: &mut renderer,
                sink: &mut sink,
                adapter,
            };
            let mut protocol = start_on(asked, &mut run);
            loop {
                let driven = match drive(protocol, connect(), &policy, &mut run).await {
                    Ok(driven) => driven,
                    Err(error) => break Err(error),
                };
                match after_process(protocol, driven, &mut run) {
                    ControlFlow::Break(outcome) => break outcome,
                    ControlFlow::Continue(next) => protocol = next,
                }
            }
        }
        Err(error) => Err(error),
    };
    run_ended(&mut renderer, &mut sink);
    if let Some(inbox) = request.parent_messages.as_ref() {
        inbox.seal();
    }
    settle(sink, outcome).await;
    Ok(())
}

/// [`run_on_channels`] for an agent that is one process.
#[cfg(test)]
pub(super) async fn run_on_channel<P: AcpAgentPolicy>(
    request: AcpSessionRequest,
    policy: P,
    channel: agent_client_protocol::Channel,
) -> anyhow::Result<()> {
    let mut channel = Some(channel);
    run_on_channels(request, policy, None, move || {
        channel.take().expect("a one-process agent connects once")
    })
    .await
}