Plan parent-first decompose, reasoning streaming, TTY input editing.

Reorder non-hit plan pipeline so the parent decomposes before spawning the child, stream DeepSeek thinking (reasoning_content) to TTY, and add Unicode-aware line editing for interactive input to fix CJK backspace corruption.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-10 11:45:58 +08:00
1 parent b6bb42e460
commit d1ddb74235
16 files changed
+606 -111

No files matched your search

+12 -2
View File
@@ -237,8 +237,18 @@ impl Vm {
Op::Input => {
let prompt = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
let text = prompt.as_display();
self.emit_prompt(&text);
let line = self.input.read_line().map_err(|e| {
let line = if self.capture {
self.emit_prompt(&text);
self.input.read_line()
} else if crate::input_feed::stdin_is_tty() {
self.input
.read_line_with_prompt(&text)
.map(|(line, _)| line)
} else {
self.emit_prompt(&text);
self.input.read_line()
}
.map_err(|e| {
let msg = e.to_string();
if msg.contains("input needs a line") {
self.err_at(span, msg)
+130 -56
View File
@@ -215,12 +215,76 @@ fn event_map(pairs: Vec<(&str, Value)>) -> Value {
)
}
/// Push stream events from one OpenAI-compatible SSE JSON object.
/// DeepSeek (and similar) may stream chain-of-thought in `delta.reasoning_content`
/// while the final answer arrives later in `delta.content`.
/// Returns `Err` only on JSON issues handled by caller; `Ok(true)` means stop (error frame).
fn push_openai_delta_events(
v: &serde_json::Value,
events: &mut Vec<Value>,
result: &mut String,
echoed: &mut bool,
saw_reasoning: &mut bool,
echo: bool,
) -> bool {
if let Some(msg) = v.get("error").and_then(|e| {
e.get("message")
.and_then(|m| m.as_str())
.or_else(|| e.as_str())
}) {
events.push(event_map(vec![
("type", Value::Text("error".into())),
("message", Value::Text(msg.into())),
]));
return true;
}
let reasoning = v
.pointer("/choices/0/delta/reasoning_content")
.and_then(|c| c.as_str())
.unwrap_or("");
if !reasoning.is_empty() {
*saw_reasoning = true;
if echo {
print!("{reasoning}");
let _ = std::io::stdout().flush();
*echoed = true;
}
events.push(event_map(vec![
("type", Value::Text("reasoning".into())),
("text", Value::Text(reasoning.into())),
]));
}
let content = v
.pointer("/choices/0/delta/content")
.and_then(|c| c.as_str())
.unwrap_or("");
if !content.is_empty() {
if echo && *saw_reasoning && result.is_empty() {
println!();
*echoed = true;
}
result.push_str(content);
if echo {
print!("{content}");
let _ = std::io::stdout().flush();
*echoed = true;
}
events.push(event_map(vec![
("type", Value::Text("delta".into())),
("text", Value::Text(content.into())),
]));
}
false
}
/// Map OpenAI-compatible chat SSE payloads → Marqdo stream events
/// (`delta` / `done` / `error`). Optional `echo` prints delta text to stdout as it arrives.
/// (`reasoning` / `delta` / `done` / `error`). Optional `echo` prints text to stdout as it arrives.
pub fn openai_chat_sse_events(text: &str, echo: bool) -> Result<Vec<Value>, String> {
let mut events = Vec::new();
let mut result = String::new();
let mut saw_done = false;
let mut echoed = false;
let mut saw_reasoning = false;
for data in sse_data_payloads(text) {
let data = data.trim();
if data.is_empty() {
@@ -232,34 +296,18 @@ pub fn openai_chat_sse_events(text: &str, echo: bool) -> Result<Vec<Value>, Stri
}
let v: serde_json::Value = serde_json::from_str(data)
.map_err(|e| format!("openai sse json: {e}"))?;
if let Some(msg) = v.get("error").and_then(|e| {
e.get("message")
.and_then(|m| m.as_str())
.or_else(|| e.as_str())
}) {
events.push(event_map(vec![
("type", Value::Text("error".into())),
("message", Value::Text(msg.into())),
]));
if push_openai_delta_events(
&v,
&mut events,
&mut result,
&mut echoed,
&mut saw_reasoning,
echo,
) {
return Ok(events);
}
let content = v
.pointer("/choices/0/delta/content")
.and_then(|c| c.as_str())
.unwrap_or("");
if !content.is_empty() {
result.push_str(content);
if echo {
print!("{content}");
let _ = std::io::stdout().flush();
}
events.push(event_map(vec![
("type", Value::Text("delta".into())),
("text", Value::Text(content.into())),
]));
}
}
if echo && !result.is_empty() {
if echo && echoed {
println!();
}
if !saw_done && events.is_empty() && result.is_empty() {
@@ -296,10 +344,14 @@ fn read_sse_body_to_events<R: BufRead>(
let mut events = Vec::new();
let mut result = String::new();
let mut data_buf: Vec<String> = Vec::new();
let mut echoed = false;
let mut saw_reasoning = false;
let flush_data = |data_buf: &mut Vec<String>,
events: &mut Vec<Value>,
result: &mut String,
echoed: &mut bool,
saw_reasoning: &mut bool,
echo: bool|
-> Result<bool, String> {
if data_buf.is_empty() {
@@ -316,33 +368,14 @@ fn read_sse_body_to_events<R: BufRead>(
}
let v: serde_json::Value =
serde_json::from_str(data).map_err(|e| format!("openai sse json: {e}"))?;
if let Some(msg) = v.get("error").and_then(|e| {
e.get("message")
.and_then(|m| m.as_str())
.or_else(|| e.as_str())
}) {
events.push(event_map(vec![
("type", Value::Text("error".into())),
("message", Value::Text(msg.into())),
]));
return Ok(true);
}
let content = v
.pointer("/choices/0/delta/content")
.and_then(|c| c.as_str())
.unwrap_or("");
if !content.is_empty() {
result.push_str(content);
if echo {
print!("{content}");
let _ = std::io::stdout().flush();
}
events.push(event_map(vec![
("type", Value::Text("delta".into())),
("text", Value::Text(content.into())),
]));
}
Ok(false)
Ok(push_openai_delta_events(
&v,
events,
result,
echoed,
saw_reasoning,
echo,
))
};
loop {
@@ -360,7 +393,14 @@ fn read_sse_body_to_events<R: BufRead>(
let line = buf.strip_suffix('\n').unwrap_or(&buf);
let line = line.strip_suffix('\r').unwrap_or(line);
if line.is_empty() {
if flush_data(&mut data_buf, &mut events, &mut result, echo)? {
if flush_data(
&mut data_buf,
&mut events,
&mut result,
&mut echoed,
&mut saw_reasoning,
echo,
)? {
break;
}
continue;
@@ -370,8 +410,15 @@ fn read_sse_body_to_events<R: BufRead>(
data_buf.push(payload.to_string());
}
}
let _ = flush_data(&mut data_buf, &mut events, &mut result, echo)?;
if echo && !result.is_empty() {
let _ = flush_data(
&mut data_buf,
&mut events,
&mut result,
&mut echoed,
&mut saw_reasoning,
echo,
)?;
if echo && echoed {
println!();
}
if events.iter().any(|e| matches!(e, Value::Map(m) if m.iter().any(|(k,v)| k == "type" && matches!(v, Value::Text(t) if t == "error")))) {
@@ -486,4 +533,31 @@ data: [DONE]\n\
_ => panic!("expected done map"),
}
}
#[test]
fn openai_sse_reasoning_then_content() {
let fixture = "\
data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"think\"}}]}\n\
\n\
data: {\"choices\":[{\"delta\":{\"content\":\"Hi\"}}]}\n\
\n\
data: [DONE]\n\
";
let ev = openai_chat_sse_events(fixture, false).unwrap();
assert_eq!(ev.len(), 3);
match &ev[0] {
Value::Map(m) => {
assert!(m.iter().any(|(k, v)| k == "type" && matches!(v, Value::Text(t) if t == "reasoning")));
assert!(m.iter().any(|(k, v)| k == "text" && matches!(v, Value::Text(t) if t == "think")));
}
_ => panic!("expected reasoning map"),
}
match &ev[2] {
Value::Map(m) => {
assert!(m.iter().any(|(k, v)| k == "type" && matches!(v, Value::Text(t) if t == "done")));
assert!(m.iter().any(|(k, v)| k == "result" && matches!(v, Value::Text(t) if t == "Hi")));
}
_ => panic!("expected done map"),
}
}
}
+187 -9
View File
@@ -1,8 +1,9 @@
//! Preset stdin lines for `input` (CLI `--stdin-file`, view form, frontmatter, tests).
//! Interactive TTY path uses Unicode-aware line editing (char backspace + redraw).
use std::collections::VecDeque;
use std::fs;
use std::io::{self, BufRead};
use std::io::{self, BufRead, Read, Write};
use std::path::Path;
use anyhow::{Context, Result};
@@ -144,6 +145,159 @@ fn strip_block_indent(line: &str) -> String {
s.trim_end_matches('\r').to_string()
}
pub fn stdin_is_tty() -> bool {
#[cfg(unix)]
{
unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }
}
#[cfg(not(unix))]
{
false
}
}
/// Piped / non-TTY: read raw bytes to newline (avoids mid-frame UTF-8 panic), lossy decode.
fn read_stdin_line_piped() -> Result<String> {
let mut buf = Vec::new();
io::stdin().lock().read_until(b'\n', &mut buf)?;
if buf.last() == Some(&b'\n') {
buf.pop();
}
if buf.last() == Some(&b'\r') {
buf.pop();
}
Ok(String::from_utf8_lossy(&buf).into_owned())
}
/// Ensure prompt has a trailing space so typed text does not glue to the last glyph.
fn normalize_prompt(prompt: &str) -> String {
if prompt.is_empty() {
return String::new();
}
if prompt.ends_with(|c: char| c.is_whitespace()) {
prompt.to_string()
} else {
format!("{prompt} ")
}
}
#[cfg(unix)]
struct TermGuard {
fd: i32,
original: libc::termios,
}
#[cfg(unix)]
impl TermGuard {
fn enter_cbreak() -> Result<Self> {
let fd = libc::STDIN_FILENO;
let mut original = unsafe { std::mem::zeroed::<libc::termios>() };
if unsafe { libc::tcgetattr(fd, &mut original) } != 0 {
return Err(io::Error::last_os_error()).context("tcgetattr");
}
let mut raw = original;
raw.c_lflag &= !(libc::ICANON | libc::ECHO);
raw.c_cc[libc::VMIN] = 1;
raw.c_cc[libc::VTIME] = 0;
if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &raw) } != 0 {
return Err(io::Error::last_os_error()).context("tcsetattr");
}
Ok(Self { fd, original })
}
}
#[cfg(unix)]
impl Drop for TermGuard {
fn drop(&mut self) {
unsafe {
libc::tcsetattr(self.fd, libc::TCSANOW, &self.original);
}
}
}
fn redraw_line(prompt: &str, buf: &str) -> Result<()> {
let mut out = io::stdout().lock();
// CR + clear whole line, then reprint (fixes CJK backspace display desync).
write!(out, "\r\x1b[2K{prompt}{buf}")?;
out.flush()?;
Ok(())
}
/// Interactive line editor: UTF-8 char backspace + full-line redraw.
#[cfg(unix)]
fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
let prompt = normalize_prompt(prompt);
let _guard = TermGuard::enter_cbreak()?;
redraw_line(&prompt, "")?;
let mut buf = String::new();
let mut pending = Vec::new();
let mut stdin = io::stdin().lock();
let mut byte = [0u8; 1];
loop {
let n = stdin.read(&mut byte)?;
if n == 0 {
// EOF
writeln!(io::stdout())?;
return Ok(buf);
}
let b = byte[0];
match b {
b'\n' | b'\r' => {
writeln!(io::stdout())?;
return Ok(buf);
}
0x7f | 0x08 => {
// Backspace / BS — delete one Unicode scalar, not one byte.
if buf.pop().is_some() {
redraw_line(&prompt, &buf)?;
}
}
0x03 => {
// Ctrl-C
writeln!(io::stdout())?;
anyhow::bail!("interrupted");
}
0x04 => {
// Ctrl-D
if buf.is_empty() && pending.is_empty() {
writeln!(io::stdout())?;
return Ok(buf);
}
}
b if b < 0x20 => {
// ignore other controls
}
b => {
pending.push(b);
match std::str::from_utf8(&pending) {
Ok(s) => {
buf.push_str(s);
pending.clear();
redraw_line(&prompt, &buf)?;
}
Err(e) if e.error_len().is_none() => {
// incomplete UTF-8 sequence — wait for more bytes
}
Err(_) => {
// invalid — drop and continue
pending.clear();
}
}
}
}
}
}
#[cfg(not(unix))]
fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
let prompt = normalize_prompt(prompt);
print!("{prompt}");
io::stdout().flush()?;
read_stdin_line_piped()
}
#[derive(Debug, Clone, Default)]
pub struct InputFeed {
queue: VecDeque<String>,
@@ -159,6 +313,7 @@ impl InputFeed {
}
/// Next line from the preset queue, or real stdin when not capturing.
/// Prefer [`Self::read_line_with_prompt`] for interactive TTY (Unicode backspace).
pub fn read_line(&mut self) -> Result<String> {
if let Some(line) = self.queue.pop_front() {
return Ok(line);
@@ -168,15 +323,23 @@ impl InputFeed {
"input needs a line (frontmatter stdin:/输入:, view Preset input, or --stdin-file)"
);
}
let mut line = String::new();
io::stdin().lock().read_line(&mut line)?;
if line.ends_with('\n') {
line.pop();
if line.ends_with('\r') {
line.pop();
}
read_stdin_line_piped()
}
/// Read a line; on a TTY, run Unicode-aware editing and draw `prompt` itself.
/// Returns `Ok((line, painted_prompt))` where `painted_prompt` is true when this
/// function already printed the prompt (caller must not `emit_prompt` again).
pub fn read_line_with_prompt(&mut self, prompt: &str) -> Result<(String, bool)> {
if let Some(line) = self.queue.pop_front() {
return Ok((line, false));
}
Ok(line)
if self.capture {
anyhow::bail!(
"input needs a line (frontmatter stdin:/输入:, view Preset input, or --stdin-file)"
);
}
let line = read_stdin_line_interactive(prompt)?;
Ok((line, true))
}
}
@@ -232,4 +395,19 @@ mod tests {
vec!["a".to_string(), String::new(), "b".to_string()]
);
}
#[test]
fn normalize_prompt_adds_space() {
assert_eq!(normalize_prompt("问?"), "问? ");
assert_eq!(normalize_prompt("问? "), "问? ");
assert_eq!(normalize_prompt(""), "");
}
#[test]
fn utf8_pop_removes_full_char() {
let mut s = String::from("帮我规划");
assert_eq!(s.pop(), Some('划'));
assert_eq!(s.pop(), Some('规'));
assert_eq!(s, "帮我");
}
}
+12 -2
View File
@@ -503,8 +503,18 @@ impl Interpreter {
.get("prompt")
.map(|v| v.as_display())
.unwrap_or_default();
self.emit_prompt(&prompt);
let line = self.input.read_line().map_err(|e| {
let line = if self.capture {
self.emit_prompt(&prompt);
self.input.read_line()
} else if crate::input_feed::stdin_is_tty() {
self.input
.read_line_with_prompt(&prompt)
.map(|(line, _)| line)
} else {
self.emit_prompt(&prompt);
self.input.read_line()
}
.map_err(|e| {
let msg = e.to_string();
if msg.contains("input needs a line") {
self.err(msg)