use std::path::Path;
use std::time::Duration;
use anyhow::Result;
use serde_json::json;
use trusty_code::cli_client::StdioRpcClient;
use trusty_code::cli_client::render::{exit_code_for_status, render_event_line};
use trusty_code::events::Event;
use trusty_code::session::Session;
use super::tcode_exe;
const POLL_INTERVAL: Duration = Duration::from_millis(500);
#[allow(clippy::too_many_arguments)]
pub async fn run(
project: &Path,
agent: &str,
task: &str,
json_output: bool,
engineer_model: Option<String>,
mode: Option<String>,
timeout_seconds: Option<u64>,
no_delegate: bool,
pm_model_flag: Option<String>,
max_turns_flag: Option<u32>,
) -> Result<i32> {
let pm_model = trusty_code::provider::resolve_pm_model_override(pm_model_flag);
let max_turns =
trusty_code::provider::resolve_max_turns(max_turns_flag).map_err(anyhow::Error::msg)?;
let exe = tcode_exe::resolve()?;
let mut client = StdioRpcClient::spawn(&exe, project)?;
let run_params = build_run_params(
agent,
task,
engineer_model,
mode,
timeout_seconds,
no_delegate,
pm_model,
max_turns,
);
let run_result = client.call("task.run", run_params).await?;
let session_id = run_result
.get("session_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("tcode run-task: daemon did not return a session_id"))?
.to_string();
let attach_result = client
.call("session.attach", json!({"session_id": session_id}))
.await?;
let replay = attach_result
.get("events")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
let mut done = false;
for raw in &replay {
if let Ok(envelope) =
serde_json::from_value::<trusty_code::events::SessionEventEnvelope>(raw.clone())
{
if !json_output {
println!("{}", render_event_line(&envelope));
}
done = done || matches!(envelope.event, Event::SessionDone { .. });
}
}
while !done {
match client.next_notification(POLL_INTERVAL).await? {
Some(envelope) => {
if !json_output {
println!("{}", render_event_line(&envelope));
}
done = matches!(envelope.event, Event::SessionDone { .. });
}
None => continue,
}
}
let status_result = client
.call("session.status", json!({"session_id": session_id}))
.await?;
client.shutdown(Duration::from_secs(5)).await?;
let session: Session = serde_json::from_value(status_result.clone())
.map_err(|e| anyhow::anyhow!("tcode run-task: malformed daemon response: {e}"))?;
if json_output {
println!(
"{}",
serde_json::to_string_pretty(&status_result)
.map_err(|e| anyhow::anyhow!("tcode run-task: failed to render JSON: {e}"))?
);
} else {
println!(
"run {}: session={} status={} mode={}",
if session.status == trusty_code::session::SessionStatus::Finished {
"finished"
} else {
"did not finish cleanly"
},
session.id,
session.status.as_str(),
session.mode.map(|m| m.as_str()).unwrap_or("unknown")
);
}
Ok(exit_code_for_status(session.status).code())
}
#[allow(clippy::too_many_arguments)]
fn build_run_params(
agent: &str,
task: &str,
engineer_model: Option<String>,
mode: Option<String>,
timeout_seconds: Option<u64>,
no_delegate: bool,
pm_model: Option<String>,
max_turns: Option<u32>,
) -> serde_json::Value {
json!({
"task_description": task,
"agent_name": agent,
"model_override": engineer_model,
"mode": mode,
"deadline_secs": timeout_seconds,
"no_delegate": no_delegate,
"pm_model": pm_model,
"max_turns": max_turns,
})
}
#[cfg(test)]
mod tests {
use super::build_run_params;
#[test]
fn run_params_carry_no_delegate() {
let on = build_run_params("engineer", "do it", None, None, None, true, None, None);
assert_eq!(on["no_delegate"], serde_json::json!(true));
assert_eq!(on["agent_name"], serde_json::json!("engineer"));
let off = build_run_params("engineer", "do it", None, None, None, false, None, None);
assert_eq!(off["no_delegate"], serde_json::json!(false));
}
#[test]
fn run_params_carry_pm_model_and_max_turns() {
let set = build_run_params(
"pm",
"do it",
None,
None,
None,
false,
Some("opus".to_string()),
Some(24),
);
assert_eq!(set["pm_model"], serde_json::json!("opus"));
assert_eq!(set["max_turns"], serde_json::json!(24));
let unset = build_run_params("pm", "do it", None, None, None, false, None, None);
assert_eq!(unset["pm_model"], serde_json::Value::Null);
assert_eq!(unset["max_turns"], serde_json::Value::Null);
}
}