use std::collections::{HashMap, HashSet};
use rho_protocol as wire;
use super::jobs::{JobId, JobRecord, JobState, JobSubject, Moved, TurnEnd};
use crate::app::agent_concurrency::{Budget, QueuePlace};
pub(super) fn session_to_wire(id: rho_sdk::SessionId) -> wire::SessionId {
wire::SessionId::new(id.into_string())
}
pub(super) fn session_from_wire(
id: &wire::SessionId,
) -> Result<rho_sdk::SessionId, rho_sdk::InvalidId> {
rho_sdk::SessionId::from_string(id.as_str())
}
impl From<crate::agent::AgentRuntime> for wire::AgentRuntime {
fn from(runtime: crate::agent::AgentRuntime) -> Self {
match runtime {
crate::agent::AgentRuntime::Rho => Self::Rho,
crate::agent::AgentRuntime::ClaudeCli => Self::ClaudeCli,
crate::agent::AgentRuntime::Antigravity => Self::Antigravity,
}
}
}
impl TryFrom<wire::AgentRuntime> for crate::agent::AgentRuntime {
type Error = wire::AgentRuntime;
fn try_from(runtime: wire::AgentRuntime) -> Result<Self, Self::Error> {
match runtime {
wire::AgentRuntime::Rho => Ok(Self::Rho),
wire::AgentRuntime::ClaudeCli => Ok(Self::ClaudeCli),
wire::AgentRuntime::Antigravity => Ok(Self::Antigravity),
unknown => Err(unknown),
}
}
}
impl From<&JobId> for wire::JobId {
fn from(id: &JobId) -> Self {
Self::new(id.as_str())
}
}
impl From<&JobState> for wire::JobState {
fn from(state: &JobState) -> Self {
match state {
JobState::Idle => Self::Idle,
JobState::Queued | JobState::Requeued => Self::Queued,
JobState::Running => Self::Running,
JobState::WaitingForInput => Self::WaitingForInput,
JobState::Ended(TurnEnd::Completed) => Self::Completed,
JobState::Ended(TurnEnd::Failed(_)) => Self::Failed,
JobState::Ended(TurnEnd::Cancelled) => Self::Cancelled,
JobState::Ended(TurnEnd::TimedOut { .. }) => Self::TimedOut,
JobState::Ended(TurnEnd::Interrupted) => Self::Interrupted,
}
}
}
fn failure(state: &JobState) -> Option<String> {
match state {
JobState::Ended(TurnEnd::Failed(error)) => Some(error.clone()),
JobState::Idle
| JobState::Queued
| JobState::Running
| JobState::Requeued
| JobState::WaitingForInput
| JobState::Ended(
TurnEnd::Completed
| TurnEnd::Cancelled
| TurnEnd::TimedOut { .. }
| TurnEnd::Interrupted,
) => None,
}
}
pub(super) fn state_event(moved: &Moved) -> wire::SessionEvent {
wire::SessionEvent::State {
state: (&moved.state).into(),
turn: moved.turn.clone(),
}
}
pub(super) fn job_summary(
record: JobRecord,
parent_job: ParentJob,
queue: Option<QueuePlace>,
undelivered: &HashSet<String>,
live: Option<wire::JobLive>,
worktree_stale: bool,
) -> wire::JobSummary {
let JobRecord {
id,
subject,
state,
workspace,
parent,
grant,
grant_limit,
admission: _,
created_at,
updated_at,
outcome: _,
turn: _,
worktree,
worktree_removed_at: _,
resume_after_restart: _,
agent,
title,
keeping: _,
} = record;
let session = subject.session().cloned().map(session_to_wire);
let child = child_role(&subject, parent_job).map(|role| {
let child = wire::ChildInfo::new(role);
let child = match agent {
Some(agent) => child.running_as(agent.id, agent.engine),
None => child,
};
match title {
Some(title) => child.titled(title),
None => child,
}
});
let (kind, run, workflow_run, worktree) = match subject {
JobSubject::Session { .. } => (wire::JobKind::Session, None, None, worktree),
JobSubject::Subagent {
run,
worktree: run_worktree,
..
} => (wire::JobKind::Subagent, run, None, run_worktree),
JobSubject::Workflow { workflow_run } => (
wire::JobKind::Workflow,
None,
Some(workflow_run.to_string()),
None,
),
};
wire::JobSummary {
id: (&id).into(),
kind,
state: (&state).into(),
workspace,
parent: parent.as_ref().map(Into::into),
grant: (!grant.is_root()).then(|| grant.into()),
grant_limit: grant_limit.map(Into::into),
session,
run,
result_pending: workflow_run
.as_ref()
.is_some_and(|run| undelivered.contains(run)),
workflow_run,
created_at,
updated_at,
error: failure(&state),
queue: queue.map(Into::into),
live,
worktree,
worktree_stale,
child,
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ParentJob {
Client,
Forgotten,
Workflow,
Agent,
}
impl ParentJob {
pub(super) fn of(records: &[JobRecord]) -> Vec<Self> {
let kinds: HashMap<&JobId, Self> = records
.iter()
.map(|record| {
let kind = match record.subject {
JobSubject::Workflow { .. } => Self::Workflow,
JobSubject::Session { .. } | JobSubject::Subagent { .. } => Self::Agent,
};
(&record.id, kind)
})
.collect();
records
.iter()
.map(|record| match &record.parent {
None => Self::Client,
Some(parent) => kinds.get(parent).copied().unwrap_or(Self::Forgotten),
})
.collect()
}
}
fn child_role(subject: &JobSubject, parent: ParentJob) -> Option<wire::ChildRole> {
match (subject, parent) {
(_, ParentJob::Client) | (JobSubject::Workflow { .. }, _) => None,
(
JobSubject::Session { .. },
ParentJob::Forgotten | ParentJob::Workflow | ParentJob::Agent,
) => Some(wire::ChildRole::Started),
(JobSubject::Subagent { .. }, ParentJob::Workflow) => Some(wire::ChildRole::WorkflowNode),
(JobSubject::Subagent { .. }, ParentJob::Forgotten | ParentJob::Agent) => {
Some(wire::ChildRole::Delegated)
}
}
}
impl From<Budget> for wire::Budget {
fn from(budget: Budget) -> Self {
match budget {
Budget::AgentConcurrency => Self::AgentConcurrency,
Budget::ClaudeAgentConcurrency => Self::ClaudeAgentConcurrency,
}
}
}
impl From<QueuePlace> for wire::QueuePlace {
fn from(place: QueuePlace) -> Self {
let QueuePlace {
budget,
limit,
position,
} = place;
let count = |value: usize| u32::try_from(value).unwrap_or(u32::MAX);
Self {
budget: budget.into(),
limit: count(limit),
position: count(position),
}
}
}
#[cfg(test)]
#[path = "wire_tests.rs"]
mod tests;