Skip to main content

harn_vm/
bridge.rs

1//! JSON-RPC 2.0 bridge for host communication.
2//!
3//! When `harn run --bridge` is used, the VM delegates builtins (llm_call,
4//! file I/O, tool execution) to a host process over stdin/stdout JSON-RPC.
5//! The host (e.g., Burin IDE) handles these requests using its own providers.
6
7use 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
18/// Default timeout for bridge calls (5 minutes).
19const DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);
20
21/// A JSON-RPC 2.0 bridge to a host process over stdin/stdout.
22///
23/// The bridge sends requests to the host on stdout and receives responses
24/// on stdin. A background task reads stdin and dispatches responses to
25/// waiting callers by request ID. All stdout writes are serialized through
26/// a mutex to prevent interleaving.
27pub struct HostBridge {
28    next_id: AtomicU64,
29    /// Pending request waiters, keyed by JSON-RPC id.
30    pending: Arc<Mutex<HashMap<u64, oneshot::Sender<serde_json::Value>>>>,
31    /// Whether the host has sent a cancel notification.
32    cancelled: Arc<AtomicBool>,
33    /// Mutex protecting stdout writes to prevent interleaving.
34    stdout_lock: Arc<std::sync::Mutex<()>>,
35    /// ACP session ID (set in ACP mode for session-scoped notifications).
36    session_id: std::sync::Mutex<String>,
37    /// Name of the currently executing Harn script (without .harn suffix).
38    script_name: std::sync::Mutex<String>,
39}
40
41// Default doesn't apply — new() spawns async tasks requiring a tokio LocalSet.
42#[allow(clippy::new_without_default)]
43impl HostBridge {
44    /// Create a new bridge and spawn the stdin reader task.
45    ///
46    /// Must be called within a tokio LocalSet (uses spawn_local for the
47    /// stdin reader since it's single-threaded).
48    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        // Stdin reader: reads JSON-RPC lines and dispatches responses
54        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, // Skip malformed lines
70                };
71
72                // Check if this is a notification from the host (no id)
73                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                // This is a response — dispatch to the waiting caller
83                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            // stdin closed — cancel any remaining pending requests by dropping senders
92            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    /// Create a bridge from pre-existing shared state.
107    ///
108    /// Unlike `new()`, does **not** spawn a stdin reader — the caller is
109    /// responsible for dispatching responses into `pending`.  This is used
110    /// by ACP mode which already has its own stdin reader.
111    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    /// Set the ACP session ID for session-scoped notifications.
128    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    /// Set the currently executing script name (without .harn suffix).
133    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    /// Get the current script name.
138    fn get_script_name(&self) -> String {
139        self.script_name.lock().unwrap_or_else(|e| e.into_inner()).clone()
140    }
141
142    /// Get the session ID.
143    fn get_session_id(&self) -> String {
144        self.session_id.lock().unwrap_or_else(|e| e.into_inner()).clone()
145    }
146
147    /// Write a complete JSON-RPC line to stdout, serialized through a mutex.
148    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    /// Send a JSON-RPC request to the host and wait for the response.
164    /// Times out after 5 minutes to prevent deadlocks.
165    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        // Register a oneshot channel to receive the response
184        let (tx, rx) = oneshot::channel();
185        {
186            let mut pending = self.pending.lock().await;
187            pending.insert(id, tx);
188        }
189
190        // Send the request (serialized through stdout mutex)
191        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            // Clean up pending entry on write failure
195            let mut pending = self.pending.lock().await;
196            pending.remove(&id);
197            return Err(e);
198        }
199
200        // Wait for the response with timeout
201        let response = match tokio::time::timeout(DEFAULT_TIMEOUT, rx).await {
202            Ok(Ok(msg)) => msg,
203            Ok(Err(_)) => {
204                // Sender dropped — host closed or stdin reader exited
205                return Err(VmError::Runtime(
206                    "Bridge: host closed connection before responding".into(),
207                ));
208            }
209            Err(_) => {
210                // Timeout — clean up pending entry
211                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        // Check for JSON-RPC error
221        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    /// Send a JSON-RPC notification to the host (no response expected).
231    /// Serialized through the stdout mutex to prevent interleaving.
232    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(&notification) {
239            let _ = self.write_line(&line);
240        }
241    }
242
243    /// Check if the host has sent a cancel notification.
244    pub fn is_cancelled(&self) -> bool {
245        self.cancelled.load(Ordering::SeqCst)
246    }
247
248    /// Send an output notification (for log/print in bridge mode).
249    pub fn send_output(&self, text: &str) {
250        self.notify("output", serde_json::json!({"text": text}));
251    }
252
253    /// Send a progress notification with optional structured data payload.
254    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    /// Send a structured log notification.
263    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    /// Send a `session/update` with `call_start` — signals the beginning of
272    /// an LLM call, tool call, or builtin call for observability.
273    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    /// Send a `session/update` with `call_progress` — a streaming token delta
301    /// from an in-flight LLM call.
302    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    /// Send a `session/update` with `call_end` — signals completion of a call.
321    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
353/// Convert a serde_json::Value to a VmValue.
354pub 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(&notification).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}