rho-coding-agent 3.7.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
//! What each action takes and returns. Front ends publish the params as
//! their input schemas and return the results as JSON, so every front end
//! answers the same call the same way.

use std::{
    collections::{BTreeMap, HashMap},
    num::NonZeroUsize,
    path::PathBuf,
    time::Duration,
};

use rho_protocol::{
    Cursor, InputRequest, InputRequestId, JobId, JobState, JobSummary, QuestionAnswer, Seq,
    SessionId, SessionWorktree, SteerId, StreamId, TurnId, TurnOutcome,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::ControlError;

/// How many sessions `list` returns by default.
//
// One screenful a model reads at once: 20 entries of about 200 bytes is
// about 4 KB, `read`'s default window.
const DEFAULT_LIST_LIMIT: usize = 20;
/// The most sessions one `list` returns: the daemon's own page limit for
/// its session catalog.
const MAX_LIST_LIMIT: usize = 1000;
/// `read`'s default window, in characters: the native `sessions` tool's.
const DEFAULT_READ_CHARS: usize = 4096;
/// `read`'s largest window: rho's default tool output limit
/// (`rho_tools::DEFAULT_MAX_OUTPUT_BYTES`).
const MAX_READ_CHARS: usize = rho_tools::DEFAULT_MAX_OUTPUT_BYTES;
/// How long `wait` waits when the call names no timeout.
const DEFAULT_WAIT_SECS: u64 = 30;
/// The longest one `wait` waits, under the hosts' own tool-call limits.
//
// Codex's default `tool_timeout_sec`, 60 s, is the smallest default among
// the hosts the docs cover; 50 s leaves the reply time to arrive. Remote
// hosts behind an HTTP time limit call again with the cursor.
pub(crate) const MAX_WAIT_SECS: u64 = 50;

/// Params of `list`.
#[derive(Debug, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct ListParams {
    /// Only sessions in this workspace, an absolute path.
    #[serde(default)]
    pub(crate) workspace: Option<PathBuf>,
    /// Only sessions in this state.
    #[serde(default)]
    pub(crate) state: Option<JobState>,
    /// Only sessions opened this way: `agent` for one opened through
    /// session control, as this tool's `new` does, and `person` for any
    /// other, such as one opened from the TUI.
    #[serde(default)]
    pub(crate) opened_by: Option<Opener>,
    /// Leave out sessions in state `idle`: opened, and not prompted since.
    #[serde(default)]
    pub(crate) hide_idle: bool,
    /// The most sessions to return, most recently changed first: 20 when
    /// absent, at most 1000.
    #[serde(default)]
    pub(crate) limit: Option<NonZeroUsize>,
}

impl ListParams {
    pub(super) fn limit(&self) -> Result<usize, ControlError> {
        let limit = self.limit.map_or(DEFAULT_LIST_LIMIT, NonZeroUsize::get);
        if limit > MAX_LIST_LIMIT {
            return Err(ControlError::Invalid(format!(
                "list limit: limit {MAX_LIST_LIMIT}, asked {limit}"
            )));
        }
        Ok(limit)
    }

    /// Whether `job` passes the filters that need no path: `state`,
    /// `opened_by`, and `hide_idle`.
    pub(super) fn keeps(&self, job: &JobSummary) -> bool {
        self.state.is_none_or(|state| job.state == state)
            && self
                .opened_by
                .is_none_or(|by| Opener::of(job.grant_limit.as_ref()) == by)
            && !(self.hide_idle && job.state == JobState::Idle)
    }
}

/// Who opened a session, as far as the daemon records it. It keeps the
/// limit a session opened under, not the client that opened it, so this
/// tells the sessions session control started from the rest, and no more.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Opener {
    /// The session opened without a session-control limit, as one opened
    /// from a person's frontend or command does: the TUI, a web UI, `rho
    /// run --detach`. So does one a command opens from a session that has
    /// no limit itself, whoever ran the command, its own agent included.
    Person,
    /// The session opened under a session-control limit, which it keeps:
    /// `rho mcp serve` or the `sessions` tool started it, or a command run
    /// inside such a session did.
    Agent,
}

impl Opener {
    /// Who opened a session whose job has `limit`
    /// (`JobSummary::grant_limit`): an agent when it has one, as every
    /// session the core starts does, one level deeper than its caller.
    fn of(limit: Option<&rho_protocol::SessionGrant>) -> Self {
        match limit {
            Some(_) => Self::Agent,
            None => Self::Person,
        }
    }
}

/// Result of `list`.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct ListResult {
    pub(crate) sessions: Vec<SessionEntry>,
    /// Whether more sessions matched than `limit` let through.
    pub(crate) more: bool,
}

/// One session, as `list` reports it.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct SessionEntry {
    pub(crate) session: SessionId,
    pub(crate) workspace: PathBuf,
    pub(crate) state: JobState,
    /// Who opened the session, so a caller can find the ones a person
    /// started from the TUI among the ones agents started.
    pub(crate) opened_by: Opener,
    /// The session's title, once it has one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) title: Option<String>,
    /// Unix time, in seconds, of the session's last state change.
    pub(crate) updated_at: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) error: Option<String>,
    /// The session whose agent started this one (#1714).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) parent: Option<SessionId>,
    /// The git worktree the session works in, with its branch (#1673).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) worktree: Option<SessionWorktree>,
}

impl SessionEntry {
    /// The entry for a session job, whose parent is the session `writers`
    /// says its parent job writes; `None` for a job that writes no session.
    /// Its title is the one the daemon follows while it has the session
    /// loaded, which starts as the saved one; else the one `saved` holds
    /// for it, which the entry takes.
    pub(super) fn of_job(
        job: JobSummary,
        writers: &HashMap<JobId, SessionId>,
        saved: &mut HashMap<SessionId, String>,
    ) -> Option<Self> {
        let session = job.session?;
        Some(Self {
            opened_by: Opener::of(job.grant_limit.as_ref()),
            title: match job.live {
                Some(live) => live.title,
                None => saved.remove(&session),
            },
            parent: job.parent.and_then(|parent| writers.get(&parent).cloned()),
            session,
            workspace: job.workspace,
            state: job.state,
            updated_at: job.updated_at,
            error: job.error,
            worktree: job.worktree,
        })
    }
}

/// Params of `read`.
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct ReadParams {
    pub(crate) session: SessionId,
    /// The first character to return; 0 when absent. Pass the last read's
    /// `next_start` to page on.
    #[serde(default)]
    pub(crate) start: usize,
    /// How many characters to return: 4096 when absent, at most 64000.
    #[serde(default)]
    pub(crate) chars: Option<NonZeroUsize>,
}

/// Which characters of a transcript `read` returns.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Window {
    start: usize,
    chars: usize,
}

impl ReadParams {
    pub(super) fn window(&self) -> Result<Window, ControlError> {
        let chars = self.chars.map_or(DEFAULT_READ_CHARS, NonZeroUsize::get);
        if chars > MAX_READ_CHARS {
            return Err(ControlError::Invalid(format!(
                "read window: limit {MAX_READ_CHARS} characters, asked {chars}"
            )));
        }
        Ok(Window {
            start: self.start,
            chars,
        })
    }
}

/// Result of `read`: characters `start..end` of the transcript's
/// `total_chars`.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ReadResult {
    pub(crate) session: SessionId,
    pub(crate) text: String,
    pub(crate) start: usize,
    pub(crate) end: usize,
    pub(crate) total_chars: usize,
    /// Where the next page starts; absent on the last.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) next_start: Option<usize>,
}

impl ReadResult {
    pub(super) fn window(session: SessionId, transcript: &str, window: Window) -> Self {
        let total_chars = transcript.chars().count();
        let start = window.start.min(total_chars);
        let end = start.saturating_add(window.chars).min(total_chars);
        Self {
            session,
            text: transcript.chars().skip(start).take(end - start).collect(),
            start,
            end,
            total_chars,
            next_start: (end < total_chars).then_some(end),
        }
    }
}

/// Params of `new`.
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct NewParams {
    /// The session's workspace, an absolute path to an existing directory.
    pub(crate) workspace: PathBuf,
    /// The first prompt, which starts the session's first turn.
    pub(crate) prompt: String,
    /// The agent the session runs as, by id, one of the workspace's; the
    /// default agent when absent.
    #[serde(default)]
    pub(crate) agent: Option<String>,
    /// The model, as `provider/model` or a model id one provider alone
    /// offers; when absent, the agent's own when it names one, else the one
    /// a person chose for the sessions the calling session starts, else the
    /// workspace's default.
    #[serde(default)]
    pub(crate) model: Option<String>,
    /// Work in a new git worktree of the workspace's repository, on a new
    /// branch, so the session's edits cannot collide with other sessions' in
    /// that repository. The branch starts from `origin`'s default branch,
    /// fetched first, or from `HEAD` when there is no `origin`, the fetch
    /// fails or takes over 30 seconds, or `git.worktree_from_remote` is off.
    /// The daemon removes the worktree once it is clean, merged, not locked,
    /// and unused for a day, keeps the branch, and adds the worktree back if
    /// the session reopens; one with unmerged work stays.
    #[serde(default)]
    pub(crate) worktree: bool,
}

/// Result of `new`: the session runs its first turn.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct NewResult {
    pub(crate) session: SessionId,
    /// The workspace the call named.
    pub(crate) workspace: PathBuf,
    /// The worktree the session works in, for a call that asked for one:
    /// its branch, its directory, and the workspace it was added from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) worktree: Option<SessionWorktree>,
}

/// Params of `prompt`. Its message is `prompt`, as `new`'s and `steer`'s
/// are, so every action that sends a message names it the same way.
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct PromptParams {
    pub(crate) session: SessionId,
    /// The prompt, which starts the session's next turn.
    // NEXT_MAJOR(rho mcp serve): drop the `text` alias of `prompt` and `steer`'s `prompt`.
    #[serde(alias = "text")]
    pub(crate) prompt: String,
}

/// Result of `prompt`: the turn began.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct PromptResult {
    pub(crate) session: SessionId,
}

/// Params of `steer`.
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct SteerParams {
    pub(crate) session: SessionId,
    /// Input for the running turn's next model request.
    // NEXT_MAJOR(rho mcp serve): drop the `text` alias of `steer`'s and `prompt`'s `prompt`.
    #[serde(alias = "text")]
    pub(crate) prompt: String,
}

/// Result of `steer`: the running turn took the input.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct SteerResult {
    pub(crate) id: SteerId,
    pub(crate) session: SessionId,
}

/// Params of `cancel`.
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct CancelParams {
    pub(crate) session: SessionId,
}

/// Result of `cancel`: the turn in progress, if any, was asked to stop.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct CancelResult {
    pub(crate) session: SessionId,
}

/// Params of `answer`: answers to a question that a session the caller
/// started asks, or `decline`. Never an approval's answer: those wait for a
/// person.
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct AnswerParams {
    /// A session this one started.
    pub(crate) session: SessionId,
    /// The question's `id`, from the `inputs` that `wait` returned.
    pub(crate) request: InputRequestId,
    /// The answers, by question `id`: the `value` of each choice picked, or
    /// your own text where the question allows other answers. Leave out to
    /// decline.
    #[serde(default)]
    pub(crate) answers: Option<BTreeMap<String, Vec<String>>>,
    /// Decline to answer the questions, instead of giving `answers`.
    #[serde(default)]
    pub(crate) decline: bool,
}

impl AnswerParams {
    /// The answer the call gives: its `answers`, or a decline.
    pub(super) fn answer(&self) -> Result<QuestionAnswer, ControlError> {
        match (&self.answers, self.decline) {
            (Some(answers), false) => Ok(QuestionAnswer::Answers {
                answers: answers.clone(),
            }),
            (None, true) => Ok(QuestionAnswer::Decline),
            (Some(_), true) | (None, false) => Err(ControlError::Invalid(
                "`answer` takes either `answers` or `decline: true`".into(),
            )),
        }
    }
}

/// Result of `answer`: the question's asker has the answer.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct AnswerResult {
    pub(crate) session: SessionId,
}

/// The result of an action on one session, with the session's title as it
/// is once the action ran, so whoever reads the result, a model or a card,
/// can name the session without a `list`. Absent before the session's first
/// title, and when looking it up failed.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct Titled<T> {
    #[serde(flatten)]
    pub(crate) result: T,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) title: Option<String>,
}

/// Params of `wait`.
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct WaitParams {
    pub(crate) session: SessionId,
    /// How long to wait, in seconds: 30 when absent, at most 50.
    #[serde(default)]
    pub(crate) timeout_secs: Option<u64>,
    /// The `cursor` the last `wait` on this session returned, to resume
    /// after what it saw.
    #[serde(default)]
    pub(crate) cursor: Option<String>,
}

impl WaitParams {
    pub(super) fn timeout(&self) -> Result<Duration, ControlError> {
        let secs = self.timeout_secs.unwrap_or(DEFAULT_WAIT_SECS);
        if secs > MAX_WAIT_SECS {
            return Err(ControlError::Invalid(format!(
                "wait timeout: limit {MAX_WAIT_SECS} s, asked {secs} s; call again with the cursor to wait longer"
            )));
        }
        Ok(Duration::from_secs(secs))
    }

    pub(super) fn cursor(&self) -> Result<Option<Cursor>, ControlError> {
        self.cursor.as_deref().map(parse_cursor).transpose()
    }
}

/// Result of `wait`. A hub reads it back from a remote's `wait`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct WaitResult {
    pub(crate) session: SessionId,
    pub(crate) state: JobState,
    /// Whether the session is done for now: it settled, with no turn under
    /// way and none the daemon will start for its background work, or it
    /// waits for a person to answer `inputs`. False with a turn that ended
    /// means background work is still due.
    pub(crate) done: bool,
    /// How the last turn ended, the final answer included, once it ended,
    /// even while `done` is false. It is final once `done` is true; until
    /// then a later turn, such as one the daemon starts to deliver
    /// background results, may replace it on the next `wait`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) outcome: Option<TurnOutcome>,
    /// The turn `state` is of: the one under way, or the last one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) turn: Option<TurnId>,
    /// What the turn or the session's subagents wait on a person for. A
    /// person answers these from a rho frontend. The session that started
    /// this one may answer a question with `answer`; no session-control
    /// action answers an approval or a plan approval.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) inputs: Vec<InputRequest>,
    /// Pass to the next `wait` on this session to resume after what this
    /// one saw; absent when it saw nothing to resume after.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) cursor: Option<String>,
}

/// A cursor as `wait` hands it out: `<stream>:<seq>`.
pub(super) fn format_cursor(cursor: &Cursor) -> String {
    format!("{}:{}", cursor.stream, cursor.seq.0)
}

fn parse_cursor(text: &str) -> Result<Cursor, ControlError> {
    let invalid = || ControlError::Invalid(format!("cursor {text:?} is not one `wait` returned"));
    let (stream, seq) = text.rsplit_once(':').ok_or_else(invalid)?;
    let seq = seq.parse().map_err(|_| invalid())?;
    if stream.is_empty() {
        return Err(invalid());
    }
    Ok(Cursor {
        stream: StreamId::new(stream),
        seq: Seq(seq),
    })
}

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