use std::{
io::{self, Write},
path::Path,
};
use clap::Subcommand;
use serde_json::json;
use super::{cancellation_listener, print_json};
use artifactize_core::agent;
use artifactize_core::inspect::session::{self, Body, Selector};
mod text;
#[derive(Debug, Subcommand)]
pub enum SessionCommand {
Show {
#[arg(value_name = "REF")]
reference: Selector,
#[arg(long)]
summary: bool,
},
Send {
#[arg(value_name = "REF")]
reference: Selector,
message: String,
},
}
pub(super) async fn execute(
state: &Path,
repo: Option<&Path>,
command: SessionCommand,
json: bool,
) -> Result<u8, String> {
match command {
SessionCommand::Show { reference, summary } => {
let shown = session::inspect(state, &reference, summary).await?;
if json {
print_json(&shown.into_json())?;
} else {
match &shown.body {
Body::Summary(summary) => text::show_summary(&shown.located, summary),
Body::Events(conversation) => text::show(&shown.located, conversation),
}
.map_err(|e| e.to_string())?;
}
}
SessionCommand::Send { reference, message } => {
let (cancellation, listener) = cancellation_listener()?;
let result = session::send_to(state, repo, &reference, &message, cancellation).await;
listener.abort();
let (located, send, answer) = result?;
let (answer_text, attempts) = match answer {
agent::FollowUp::Started {
answer: Ok(text),
attempts,
} => (text, attempts),
agent::FollowUp::NotStarted(failure)
| agent::FollowUp::Started {
answer: Err(failure),
..
} => {
return Err(format!(
"The follow-up failed ({}): {}",
failure.code.as_str(),
failure.message
));
}
};
if json {
print_json(&json!({
"reference": located.reference.as_ref().map(ToString::to_string),
"sessionId": located.id.as_str(),
"requestId": located.request.request.id.as_str(),
"send": send.number,
"filesChanged": send.files_changed,
"answer": answer_text,
"usage": attempts,
}))?;
} else {
let mut out = io::stdout().lock();
let suffix = if send.files_changed == Some(true) {
" · files changed since this review"
} else {
""
};
writeln!(
out,
"Session {} · follow-up {} · {}{suffix}\n\n{}",
located.id,
send.number,
send.model,
answer_text.trim_end()
)
.map_err(|e| e.to_string())?;
}
}
}
Ok(0)
}