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;
const DEFAULT_LIST_LIMIT: usize = 20;
const MAX_LIST_LIMIT: usize = 1000;
const DEFAULT_READ_CHARS: usize = 4096;
const MAX_READ_CHARS: usize = rho_tools::DEFAULT_MAX_OUTPUT_BYTES;
const DEFAULT_WAIT_SECS: u64 = 30;
pub(crate) const MAX_WAIT_SECS: u64 = 50;
#[derive(Debug, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct ListParams {
#[serde(default)]
pub(crate) workspace: Option<PathBuf>,
#[serde(default)]
pub(crate) state: Option<JobState>,
#[serde(default)]
pub(crate) opened_by: Option<Opener>,
#[serde(default)]
pub(crate) hide_idle: bool,
#[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)
}
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)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Opener {
Person,
Agent,
}
impl Opener {
fn of(limit: Option<&rho_protocol::SessionGrant>) -> Self {
match limit {
Some(_) => Self::Agent,
None => Self::Person,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct ListResult {
pub(crate) sessions: Vec<SessionEntry>,
pub(crate) more: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct SessionEntry {
pub(crate) session: SessionId,
pub(crate) workspace: PathBuf,
pub(crate) state: JobState,
pub(crate) opened_by: Opener,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) title: Option<String>,
pub(crate) updated_at: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) error: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) parent: Option<SessionId>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) worktree: Option<SessionWorktree>,
}
impl SessionEntry {
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,
})
}
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct ReadParams {
pub(crate) session: SessionId,
#[serde(default)]
pub(crate) start: usize,
#[serde(default)]
pub(crate) chars: Option<NonZeroUsize>,
}
#[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,
})
}
}
#[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,
#[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),
}
}
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct NewParams {
pub(crate) workspace: PathBuf,
pub(crate) prompt: String,
#[serde(default)]
pub(crate) agent: Option<String>,
#[serde(default)]
pub(crate) model: Option<String>,
#[serde(default)]
pub(crate) worktree: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct NewResult {
pub(crate) session: SessionId,
pub(crate) workspace: PathBuf,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) worktree: Option<SessionWorktree>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct PromptParams {
pub(crate) session: SessionId,
#[serde(alias = "text")]
pub(crate) prompt: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct PromptResult {
pub(crate) session: SessionId,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct SteerParams {
pub(crate) session: SessionId,
#[serde(alias = "text")]
pub(crate) prompt: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct SteerResult {
pub(crate) id: SteerId,
pub(crate) session: SessionId,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct CancelParams {
pub(crate) session: SessionId,
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct CancelResult {
pub(crate) session: SessionId,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct AnswerParams {
pub(crate) session: SessionId,
pub(crate) request: InputRequestId,
#[serde(default)]
pub(crate) answers: Option<BTreeMap<String, Vec<String>>>,
#[serde(default)]
pub(crate) decline: bool,
}
impl AnswerParams {
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(),
)),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct AnswerResult {
pub(crate) session: SessionId,
}
#[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>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct WaitParams {
pub(crate) session: SessionId,
#[serde(default)]
pub(crate) timeout_secs: Option<u64>,
#[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()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct WaitResult {
pub(crate) session: SessionId,
pub(crate) state: JobState,
pub(crate) done: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) outcome: Option<TurnOutcome>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) turn: Option<TurnId>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) inputs: Vec<InputRequest>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) cursor: Option<String>,
}
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;