Skip to main content

agent_commander/
live_input.rs

1//! Live input for a running agent (issue #57).
2//!
3//! Claude Code (`-p --input-format stream-json`), Qwen Code and
4//! @link-assistant/agent (`--input-format stream-json`) keep reading NDJSON
5//! user frames from stdin while they work, so a caller can queue follow-up
6//! messages into the same session. upcomputer steers and queues messages into
7//! running Claude turns, and hive-mind feeds new PR comments into a running
8//! session; both need the same frames. Claude and Qwen also accept an
9//! `interrupt` control request, which ends the running turn (the Claude Agent
10//! SDK's `Query.interrupt()`).
11
12use serde_json::{json, Value};
13use std::sync::atomic::{AtomicU64, Ordering};
14
15use crate::Agent;
16
17static INTERRUPT_SEQUENCE: AtomicU64 = AtomicU64::new(0);
18
19/// Tools whose stdin frames use the Anthropic message envelope and that
20/// answer an `interrupt` control request.
21fn uses_envelope(tool: &str) -> bool {
22    matches!(tool, "claude" | "qwen")
23}
24
25/// Whether a tool reads live NDJSON user frames from stdin.
26pub fn supports_live_input(tool: &str) -> bool {
27    matches!(tool, "claude" | "qwen" | "agent")
28}
29
30/// Error text for tools without a live input channel.
31pub 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
37/// Build one user-message frame.
38///
39/// `content` is text, or Anthropic content blocks (text, image) for Claude
40/// and Qwen. `system_prompt` is prepended to text for qwen and agent, which
41/// have no separate system-prompt channel on stdin.
42pub 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
71/// Build the control request that interrupts the running turn.
72pub 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        // The deadline can close stdin while the initial frame is still being
100        // written. Let stop() collect the timeout and whatever the tool emitted.
101        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    /// Queue a follow-up user message into the running session (requires
127    /// [`crate::AgentOptions::live_input`]).
128    ///
129    /// `content` is text, or content blocks for Claude and Qwen. The tool
130    /// reads it after (or, for Claude, alongside) the current turn.
131    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    /// Ask Claude or Qwen to end the running turn; queued messages still run.
137    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    /// Close stdin: the tool finishes the queued input and exits.
143    ///
144    /// Returns whether input was open. `stop` and `cancel` also end it.
145    pub fn end_input(&mut self) -> bool {
146        self.process_handle
147            .as_mut()
148            .is_some_and(crate::ProcessHandle::end_stdin)
149    }
150}