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);
pub async fn run(
project: &Path,
agent: &str,
task: &str,
json_output: bool,
engineer_model: Option<String>,
mode: Option<String>,
timeout_seconds: Option<u64>,
) -> Result<i32> {
let exe = tcode_exe::resolve()?;
let mut client = StdioRpcClient::spawn(&exe, project)?;
let run_params = json!({
"task_description": task,
"agent_name": agent,
"model_override": engineer_model,
"mode": mode,
"deadline_secs": timeout_seconds,
});
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())
}