agent_commander/
live_input.rs1use serde_json::{json, Value};
13use std::sync::atomic::{AtomicU64, Ordering};
14
15use crate::Agent;
16
17static INTERRUPT_SEQUENCE: AtomicU64 = AtomicU64::new(0);
18
19fn uses_envelope(tool: &str) -> bool {
22 matches!(tool, "claude" | "qwen")
23}
24
25pub fn supports_live_input(tool: &str) -> bool {
27 matches!(tool, "claude" | "qwen" | "agent")
28}
29
30pub fn live_input_unsupported_error(tool: &str) -> String {
32 format!(
33 "Tool \"{tool}\" does not read live input (no stream-json stdin channel). Choose one of: claude, qwen, agent; or run without live_input."
34 )
35}
36
37pub fn build_user_input_frame(
43 tool: &str,
44 content: &Value,
45 system_prompt: Option<&str>,
46) -> Result<Value, String> {
47 if tool == "claude" {
48 let content = if content.is_null() {
49 json!("")
50 } else {
51 content.clone()
52 };
53 return Ok(json!({"type": "user", "message": {"role": "user", "content": content}}));
54 }
55 if uses_envelope(tool) && content.is_array() {
56 return Ok(json!({"type": "user", "message": {"role": "user", "content": content}}));
57 }
58 let text = match content {
59 Value::String(text) => text.as_str(),
60 Value::Null => "",
61 _ => return Err(format!("Tool \"{tool}\" accepts only text live input")),
62 };
63 let text = system_prompt.map_or_else(|| text.to_string(), |sys| format!("{sys}\n\n{text}"));
64 Ok(if uses_envelope(tool) {
65 json!({"type": "user", "message": {"role": "user", "content": text}})
66 } else {
67 json!({"type": "user", "message": text})
68 })
69}
70
71pub fn build_interrupt_frame(tool: &str, request_id: Option<&str>) -> Result<Value, String> {
73 if !uses_envelope(tool) {
74 return Err(format!(
75 "Tool \"{tool}\" has no interrupt control request. Choose claude or qwen, or stop the agent instead."
76 ));
77 }
78 let sequence = INTERRUPT_SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1;
79 let request_id = request_id.map_or_else(
80 || format!("interrupt-{}-{sequence}", std::process::id()),
81 str::to_string,
82 );
83 Ok(json!({
84 "type": "control_request",
85 "request_id": request_id,
86 "request": {"subtype": "interrupt"}
87 }))
88}
89
90impl Agent {
91 pub(crate) async fn write_input_frame(&mut self, frame: &Value) -> Result<(), String> {
92 if !self.options.live_input {
93 return Err("Agent was not started with live_input".to_string());
94 }
95 let handle = self
96 .process_handle
97 .as_mut()
98 .filter(|handle| handle.has_stdin())
99 .ok_or("Agent input is closed (not started, ended, or stopped)")?;
100 handle
101 .write_stdin(&format!("{frame}\n"))
102 .await
103 .map_err(|error| error.to_string())
104 }
105
106 pub async fn send_message(&mut self, content: impl Into<Value>) -> Result<(), String> {
112 let frame = build_user_input_frame(&self.options.tool, &content.into(), None)?;
113 self.write_input_frame(&frame).await
114 }
115
116 pub async fn interrupt(&mut self) -> Result<(), String> {
118 let frame = build_interrupt_frame(&self.options.tool, None)?;
119 self.write_input_frame(&frame).await
120 }
121
122 pub fn end_input(&mut self) -> bool {
126 self.process_handle
127 .as_mut()
128 .is_some_and(crate::ProcessHandle::end_stdin)
129 }
130}