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_initial_input_frame(&mut self) -> Result<(), String> {
92 let prompt = self.options.prompt.clone().map_or(Value::Null, Value::from);
93 let frame = build_user_input_frame(
94 &self.options.tool,
95 &prompt,
96 self.options.system_prompt.as_deref(),
97 )?;
98 let result = self.write_input_frame(&frame).await;
99 if self
102 .process_handle
103 .as_ref()
104 .is_some_and(crate::executor::ProcessHandle::timed_out)
105 {
106 return Ok(());
107 }
108 result
109 }
110
111 pub(crate) async fn write_input_frame(&mut self, frame: &Value) -> Result<(), String> {
112 if !self.options.live_input {
113 return Err("Agent was not started with live_input".to_string());
114 }
115 let handle = self
116 .process_handle
117 .as_mut()
118 .filter(|handle| handle.has_stdin())
119 .ok_or("Agent input is closed (not started, ended, or stopped)")?;
120 handle
121 .write_stdin(&format!("{frame}\n"))
122 .await
123 .map_err(|error| error.to_string())
124 }
125
126 pub async fn send_message(&mut self, content: impl Into<Value>) -> Result<(), String> {
132 let frame = build_user_input_frame(&self.options.tool, &content.into(), None)?;
133 self.write_input_frame(&frame).await
134 }
135
136 pub async fn interrupt(&mut self) -> Result<(), String> {
138 let frame = build_interrupt_frame(&self.options.tool, None)?;
139 self.write_input_frame(&frame).await
140 }
141
142 pub fn end_input(&mut self) -> bool {
146 self.process_handle
147 .as_mut()
148 .is_some_and(crate::ProcessHandle::end_stdin)
149 }
150}