1use std::collections::HashMap;
8use std::io::Write;
9use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
10use std::sync::Arc;
11use std::time::Duration;
12
13use tokio::io::AsyncBufReadExt;
14use tokio::sync::{oneshot, Mutex};
15
16use crate::value::{VmError, VmValue};
17
18const DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);
20
21pub struct HostBridge {
28 next_id: AtomicU64,
29 pending: Arc<Mutex<HashMap<u64, oneshot::Sender<serde_json::Value>>>>,
31 cancelled: Arc<AtomicBool>,
33 stdout_lock: Arc<std::sync::Mutex<()>>,
35 session_id: std::sync::Mutex<String>,
37 script_name: std::sync::Mutex<String>,
39}
40
41#[allow(clippy::new_without_default)]
43impl HostBridge {
44 pub fn new() -> Self {
49 let pending: Arc<Mutex<HashMap<u64, oneshot::Sender<serde_json::Value>>>> =
50 Arc::new(Mutex::new(HashMap::new()));
51 let cancelled = Arc::new(AtomicBool::new(false));
52
53 let pending_clone = pending.clone();
55 let cancelled_clone = cancelled.clone();
56 tokio::task::spawn_local(async move {
57 let stdin = tokio::io::stdin();
58 let reader = tokio::io::BufReader::new(stdin);
59 let mut lines = reader.lines();
60
61 while let Ok(Some(line)) = lines.next_line().await {
62 let line = line.trim().to_string();
63 if line.is_empty() {
64 continue;
65 }
66
67 let msg: serde_json::Value = match serde_json::from_str(&line) {
68 Ok(v) => v,
69 Err(_) => continue, };
71
72 if msg.get("id").is_none() {
74 if let Some(method) = msg["method"].as_str() {
75 if method == "cancel" {
76 cancelled_clone.store(true, Ordering::SeqCst);
77 }
78 }
79 continue;
80 }
81
82 if let Some(id) = msg["id"].as_u64() {
84 let mut pending = pending_clone.lock().await;
85 if let Some(sender) = pending.remove(&id) {
86 let _ = sender.send(msg);
87 }
88 }
89 }
90
91 let mut pending = pending_clone.lock().await;
93 pending.clear();
94 });
95
96 Self {
97 next_id: AtomicU64::new(1),
98 pending,
99 cancelled,
100 stdout_lock: Arc::new(std::sync::Mutex::new(())),
101 session_id: std::sync::Mutex::new(String::new()),
102 script_name: std::sync::Mutex::new(String::new()),
103 }
104 }
105
106 pub fn from_parts(
112 pending: Arc<Mutex<HashMap<u64, oneshot::Sender<serde_json::Value>>>>,
113 cancelled: Arc<AtomicBool>,
114 stdout_lock: Arc<std::sync::Mutex<()>>,
115 start_id: u64,
116 ) -> Self {
117 Self {
118 next_id: AtomicU64::new(start_id),
119 pending,
120 cancelled,
121 stdout_lock,
122 session_id: std::sync::Mutex::new(String::new()),
123 script_name: std::sync::Mutex::new(String::new()),
124 }
125 }
126
127 pub fn set_session_id(&self, id: &str) {
129 *self.session_id.lock().unwrap_or_else(|e| e.into_inner()) = id.to_string();
130 }
131
132 pub fn set_script_name(&self, name: &str) {
134 *self.script_name.lock().unwrap_or_else(|e| e.into_inner()) = name.to_string();
135 }
136
137 fn get_script_name(&self) -> String {
139 self.script_name.lock().unwrap_or_else(|e| e.into_inner()).clone()
140 }
141
142 fn get_session_id(&self) -> String {
144 self.session_id.lock().unwrap_or_else(|e| e.into_inner()).clone()
145 }
146
147 fn write_line(&self, line: &str) -> Result<(), VmError> {
149 let _guard = self.stdout_lock.lock().unwrap_or_else(|e| e.into_inner());
150 let mut stdout = std::io::stdout().lock();
151 stdout
152 .write_all(line.as_bytes())
153 .map_err(|e| VmError::Runtime(format!("Bridge write error: {e}")))?;
154 stdout
155 .write_all(b"\n")
156 .map_err(|e| VmError::Runtime(format!("Bridge write error: {e}")))?;
157 stdout
158 .flush()
159 .map_err(|e| VmError::Runtime(format!("Bridge flush error: {e}")))?;
160 Ok(())
161 }
162
163 pub async fn call(
166 &self,
167 method: &str,
168 params: serde_json::Value,
169 ) -> Result<serde_json::Value, VmError> {
170 if self.is_cancelled() {
171 return Err(VmError::Runtime("Bridge: operation cancelled".into()));
172 }
173
174 let id = self.next_id.fetch_add(1, Ordering::SeqCst);
175
176 let request = serde_json::json!({
177 "jsonrpc": "2.0",
178 "id": id,
179 "method": method,
180 "params": params,
181 });
182
183 let (tx, rx) = oneshot::channel();
185 {
186 let mut pending = self.pending.lock().await;
187 pending.insert(id, tx);
188 }
189
190 let line = serde_json::to_string(&request)
192 .map_err(|e| VmError::Runtime(format!("Bridge serialization error: {e}")))?;
193 if let Err(e) = self.write_line(&line) {
194 let mut pending = self.pending.lock().await;
196 pending.remove(&id);
197 return Err(e);
198 }
199
200 let response = match tokio::time::timeout(DEFAULT_TIMEOUT, rx).await {
202 Ok(Ok(msg)) => msg,
203 Ok(Err(_)) => {
204 return Err(VmError::Runtime(
206 "Bridge: host closed connection before responding".into(),
207 ));
208 }
209 Err(_) => {
210 let mut pending = self.pending.lock().await;
212 pending.remove(&id);
213 return Err(VmError::Runtime(format!(
214 "Bridge: host did not respond to '{method}' within {}s",
215 DEFAULT_TIMEOUT.as_secs()
216 )));
217 }
218 };
219
220 if let Some(error) = response.get("error") {
222 let message = error["message"].as_str().unwrap_or("Unknown host error");
223 let code = error["code"].as_i64().unwrap_or(-1);
224 return Err(VmError::Runtime(format!("Host error ({code}): {message}")));
225 }
226
227 Ok(response["result"].clone())
228 }
229
230 pub fn notify(&self, method: &str, params: serde_json::Value) {
233 let notification = serde_json::json!({
234 "jsonrpc": "2.0",
235 "method": method,
236 "params": params,
237 });
238 if let Ok(line) = serde_json::to_string(¬ification) {
239 let _ = self.write_line(&line);
240 }
241 }
242
243 pub fn is_cancelled(&self) -> bool {
245 self.cancelled.load(Ordering::SeqCst)
246 }
247
248 pub fn send_output(&self, text: &str) {
250 self.notify("output", serde_json::json!({"text": text}));
251 }
252
253 pub fn send_progress(&self, phase: &str, message: &str, data: Option<serde_json::Value>) {
255 let mut payload = serde_json::json!({"phase": phase, "message": message});
256 if let Some(d) = data {
257 payload["data"] = d;
258 }
259 self.notify("progress", payload);
260 }
261
262 pub fn send_log(&self, level: &str, message: &str, fields: Option<serde_json::Value>) {
264 let mut payload = serde_json::json!({"level": level, "message": message});
265 if let Some(f) = fields {
266 payload["fields"] = f;
267 }
268 self.notify("log", payload);
269 }
270
271 pub fn send_call_start(
274 &self,
275 call_id: &str,
276 call_type: &str,
277 name: &str,
278 metadata: serde_json::Value,
279 ) {
280 let session_id = self.get_session_id();
281 let script = self.get_script_name();
282 self.notify(
283 "session/update",
284 serde_json::json!({
285 "sessionId": session_id,
286 "update": {
287 "sessionUpdate": "call_start",
288 "content": {
289 "call_id": call_id,
290 "call_type": call_type,
291 "name": name,
292 "script": script,
293 "metadata": metadata,
294 },
295 },
296 }),
297 );
298 }
299
300 pub fn send_call_progress(&self, call_id: &str, delta: &str, accumulated_tokens: u64) {
303 let session_id = self.get_session_id();
304 self.notify(
305 "session/update",
306 serde_json::json!({
307 "sessionId": session_id,
308 "update": {
309 "sessionUpdate": "call_progress",
310 "content": {
311 "call_id": call_id,
312 "delta": delta,
313 "accumulated_tokens": accumulated_tokens,
314 },
315 },
316 }),
317 );
318 }
319
320 pub fn send_call_end(
322 &self,
323 call_id: &str,
324 call_type: &str,
325 name: &str,
326 duration_ms: u64,
327 status: &str,
328 metadata: serde_json::Value,
329 ) {
330 let session_id = self.get_session_id();
331 let script = self.get_script_name();
332 self.notify(
333 "session/update",
334 serde_json::json!({
335 "sessionId": session_id,
336 "update": {
337 "sessionUpdate": "call_end",
338 "content": {
339 "call_id": call_id,
340 "call_type": call_type,
341 "name": name,
342 "script": script,
343 "duration_ms": duration_ms,
344 "status": status,
345 "metadata": metadata,
346 },
347 },
348 }),
349 );
350 }
351}
352
353pub fn json_result_to_vm_value(val: &serde_json::Value) -> VmValue {
355 crate::stdlib::json_to_vm_value(val)
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361
362 #[test]
363 fn test_json_rpc_request_format() {
364 let request = serde_json::json!({
365 "jsonrpc": "2.0",
366 "id": 1,
367 "method": "llm_call",
368 "params": {
369 "prompt": "Hello",
370 "system": "Be helpful",
371 },
372 });
373 let s = serde_json::to_string(&request).unwrap();
374 assert!(s.contains("\"jsonrpc\":\"2.0\""));
375 assert!(s.contains("\"id\":1"));
376 assert!(s.contains("\"method\":\"llm_call\""));
377 }
378
379 #[test]
380 fn test_json_rpc_notification_format() {
381 let notification = serde_json::json!({
382 "jsonrpc": "2.0",
383 "method": "output",
384 "params": {"text": "[harn] hello\n"},
385 });
386 let s = serde_json::to_string(¬ification).unwrap();
387 assert!(s.contains("\"method\":\"output\""));
388 assert!(!s.contains("\"id\""));
389 }
390
391 #[test]
392 fn test_json_rpc_error_response_parsing() {
393 let response = serde_json::json!({
394 "jsonrpc": "2.0",
395 "id": 1,
396 "error": {
397 "code": -32600,
398 "message": "Invalid request",
399 },
400 });
401 assert!(response.get("error").is_some());
402 assert_eq!(
403 response["error"]["message"].as_str().unwrap(),
404 "Invalid request"
405 );
406 }
407
408 #[test]
409 fn test_json_rpc_success_response_parsing() {
410 let response = serde_json::json!({
411 "jsonrpc": "2.0",
412 "id": 1,
413 "result": {
414 "text": "Hello world",
415 "input_tokens": 10,
416 "output_tokens": 5,
417 },
418 });
419 assert!(response.get("result").is_some());
420 assert_eq!(response["result"]["text"].as_str().unwrap(), "Hello world");
421 }
422
423 #[test]
424 fn test_cancelled_flag() {
425 let cancelled = Arc::new(AtomicBool::new(false));
426 assert!(!cancelled.load(Ordering::SeqCst));
427 cancelled.store(true, Ordering::SeqCst);
428 assert!(cancelled.load(Ordering::SeqCst));
429 }
430
431 #[test]
432 fn test_json_result_to_vm_value_string() {
433 let val = serde_json::json!("hello");
434 let vm_val = json_result_to_vm_value(&val);
435 assert_eq!(vm_val.display(), "hello");
436 }
437
438 #[test]
439 fn test_json_result_to_vm_value_dict() {
440 let val = serde_json::json!({"name": "test", "count": 42});
441 let vm_val = json_result_to_vm_value(&val);
442 let VmValue::Dict(d) = &vm_val else {
443 unreachable!("Expected Dict, got {:?}", vm_val);
444 };
445 assert_eq!(d.get("name").unwrap().display(), "test");
446 assert_eq!(d.get("count").unwrap().display(), "42");
447 }
448
449 #[test]
450 fn test_json_result_to_vm_value_null() {
451 let val = serde_json::json!(null);
452 let vm_val = json_result_to_vm_value(&val);
453 assert!(matches!(vm_val, VmValue::Nil));
454 }
455
456 #[test]
457 fn test_json_result_to_vm_value_nested() {
458 let val = serde_json::json!({
459 "text": "response",
460 "tool_calls": [
461 {"id": "tc_1", "name": "read_file", "arguments": {"path": "foo.rs"}}
462 ],
463 "input_tokens": 100,
464 "output_tokens": 50,
465 });
466 let vm_val = json_result_to_vm_value(&val);
467 let VmValue::Dict(d) = &vm_val else {
468 unreachable!("Expected Dict, got {:?}", vm_val);
469 };
470 assert_eq!(d.get("text").unwrap().display(), "response");
471 let VmValue::List(list) = d.get("tool_calls").unwrap() else {
472 unreachable!("Expected List for tool_calls");
473 };
474 assert_eq!(list.len(), 1);
475 }
476
477 #[test]
478 fn test_timeout_duration() {
479 assert_eq!(DEFAULT_TIMEOUT.as_secs(), 300);
480 }
481}