1use anyhow::{Context, Result};
17use robonix_atlas::client::{self as atlas_client, AtlasClient};
18use std::io::{self, Write};
19use std::time::{SystemTime, UNIX_EPOCH};
20use tokio_stream::StreamExt;
21use tonic::Request;
22use uuid::Uuid;
23
24use crate::pb::contracts::robonix_system_pilot_client::RobonixSystemPilotClient;
25use crate::pb::pilot::rtdl_node_state::RtdlNodeStateEnum;
26use crate::pb::pilot::{CapabilityCall, Plan, Task};
27
28const EVT_TEXT_CHUNK: u32 = 0;
30const EVT_PLAN: u32 = 1;
31const EVT_BATCH_RESULT: u32 = 2;
32const EVT_STATUS: u32 = 3;
33const EVT_FINAL_TEXT: u32 = 4;
34
35const STATE_FAILED: u32 = 2;
36const CONSUMER_ID: &str = "rbnx-cli/ask";
37
38pub async fn execute(
39 server: &str,
40 prompt: &str,
41 json: bool,
42 session: Option<String>,
43) -> Result<()> {
44 let mut atlas = AtlasClient::connect(server)
45 .await
46 .with_context(|| format!("connect to atlas at '{server}'"))?;
47 let (channel_id, pilot_cap_id, channel) =
48 atlas_client::connect_to_capability(&mut atlas, CONSUMER_ID, "robonix/system/pilot")
49 .await
50 .context("locate pilot via atlas")?;
51 if !json {
52 eprintln!("[ask] connected to pilot '{pilot_cap_id}' (channel {channel_id})");
53 }
54 let mut client = RobonixSystemPilotClient::new(channel);
55
56 let session_id = session.unwrap_or_else(|| Uuid::new_v4().to_string());
57 let task = Task {
58 task_id: Uuid::new_v4().to_string(),
59 session_id: session_id.clone(),
60 source: 0, text: prompt.to_string(),
62 audio_data: vec![],
63 context_json: String::new(),
64 timestamp_ms: now_ms(),
65 };
66 let mut stream = client
67 .submit_task(Request::new(task))
68 .await
69 .context("SubmitTask RPC failed")?
70 .into_inner();
71
72 let stdout = io::stdout();
73 let mut out = stdout.lock();
74 let mut last_was_chunk = false;
75 let mut had_failure = false;
76
77 while let Some(event) = stream.next().await {
78 let event = event.context("pilot stream error")?;
79 if json {
80 let v = serde_json::json!({
83 "event_kind": event.event_kind,
84 "session_id": event.session_id,
85 "text_chunk": event.text_chunk,
86 "final_text": event.final_text,
87 "plan": event.plan.as_ref().map(|p| serde_json::json!({
88 "round": p.round,
89 "root_index": p.root_index,
90 "calls": plan_calls(p).into_iter().map(|c| serde_json::json!({
91 "call_id": c.call_id,
92 "provider_id": c.provider_id,
93 "contract_id": c.contract_id,
94 "args_json": c.args_json,
95 })).collect::<Vec<_>>(),
96 })),
97 "batch_result": event.batch_result.as_ref().map(|b| serde_json::json!({
98 "round": b.round,
99 "any_failed": b.any_failed,
100 "results": b.results.iter().map(|r| serde_json::json!({
103 "node_index": r.node_index,
104 "node_kind": r.node_kind,
105 "state": r.state,
106 "op_id": r.op_id,
107 "description": r.description,
108 "operator_detail": r.operator_detail,
109 "leaf_result": r.leaf_result.as_ref().map(|lr| serde_json::json!({
110 "call_id": lr.call_id,
111 "contract_id": lr.contract_id,
112 "success": lr.success,
113 "output": lr.output,
114 "error": lr.error,
115 })),
116 })).collect::<Vec<_>>(),
117 })),
118 "status": event.status.as_ref().map(|s| serde_json::json!({
119 "state": s.state,
120 "message": s.message,
121 })),
122 });
123 writeln!(out, "{v}")?;
124 out.flush()?;
125 continue;
126 }
127
128 match event.event_kind {
132 EVT_TEXT_CHUNK => {
133 let chunk = event.text_chunk;
134 if chunk.is_empty() {
135 continue;
136 }
137 if !last_was_chunk {
138 write!(out, "\n[agent] ")?;
139 }
140 write!(out, "{chunk}")?;
141 out.flush()?;
142 last_was_chunk = true;
143 }
144 EVT_PLAN => {
145 if let Some(plan) = event.plan {
146 if last_was_chunk {
147 writeln!(out)?;
148 last_was_chunk = false;
149 }
150 let leaves: Vec<String> = plan_calls(&plan)
151 .into_iter()
152 .map(|c| {
153 c.contract_id
154 .rsplit_once('/')
155 .map(|(_, l)| l.to_string())
156 .unwrap_or_else(|| c.contract_id.clone())
157 })
158 .collect();
159 writeln!(out, "[plan r{}] {}", plan.round, leaves.join(", "))?;
160 out.flush()?;
161 }
162 }
163 EVT_BATCH_RESULT => {
164 if let Some(batch) = event.batch_result {
165 if last_was_chunk {
166 writeln!(out)?;
167 last_was_chunk = false;
168 }
169 for r in &batch.results {
170 let success = r.state == RtdlNodeStateEnum::Succeeded as u32;
171 let (label, body) = match r.leaf_result.as_ref() {
174 Some(lr) => (
175 lr.contract_id
176 .rsplit_once('/')
177 .map(|(_, l)| l.to_string())
178 .unwrap_or_else(|| lr.contract_id.clone()),
179 if lr.success {
180 lr.output.clone()
181 } else {
182 lr.error.clone()
183 },
184 ),
185 None if !r.description.is_empty() => {
186 (r.description.clone(), r.operator_detail.clone())
187 }
188 None => (format!("node{}", r.node_index), r.operator_detail.clone()),
189 };
190 let summary = compact_one_line(&body, 200);
191 let mark = if success { "✓" } else { "✗" };
192 writeln!(out, " [{mark} {label}] {summary}")?;
193 }
194 out.flush()?;
195 }
196 }
197 EVT_STATUS => {
198 if let Some(s) = event.status {
199 if last_was_chunk {
200 writeln!(out)?;
201 last_was_chunk = false;
202 }
203 if s.state == STATE_FAILED {
204 had_failure = true;
205 writeln!(out, "[status FAILED] {}", s.message)?;
206 } else if !s.message.is_empty() {
207 writeln!(out, "[status] {}", s.message)?;
208 }
209 out.flush()?;
210 }
211 }
212 EVT_FINAL_TEXT => {
213 }
215 _ => {}
216 }
217 }
218
219 if last_was_chunk {
220 writeln!(out)?;
221 }
222 let _ = atlas.disconnect_capability(&channel_id).await;
223 if had_failure {
224 anyhow::bail!("pilot reported FAILED status");
225 }
226 Ok(())
227}
228
229fn compact_one_line(s: &str, n: usize) -> String {
230 let flat: String = s
231 .chars()
232 .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
233 .collect();
234 if flat.chars().count() > n {
235 let mut out: String = flat.chars().take(n).collect();
236 out.push('…');
237 out
238 } else {
239 flat
240 }
241}
242
243fn plan_calls(plan: &Plan) -> Vec<&CapabilityCall> {
244 plan.nodes
245 .iter()
246 .filter_map(|node| node.call.as_ref())
247 .collect()
248}
249
250fn now_ms() -> u64 {
251 SystemTime::now()
252 .duration_since(UNIX_EPOCH)
253 .unwrap_or_default()
254 .as_millis() as u64
255}