Skip to main content

tea_cli/modes/
print.rs

1use std::io::{Read, Write};
2
3use tea::RuntimeCommandOutcome;
4use tea_coding::CodingAgentService;
5use tea_protocol::{CanonicalMessage, ContentBlock, SessionId};
6use tokio::sync::mpsc;
7
8use crate::args::{CliArgs, SessionSelection};
9use crate::{CliBootstrap, CliFailure, ExitCategory};
10
11/// Maximum aggregate UTF-8 bytes accepted as one initial prompt.
12pub const MAX_INITIAL_PROMPT_BYTES: usize = 256 * 1024;
13
14/// Runs script-safe print mode with injected streams.
15///
16/// # Errors
17///
18/// Returns stable categorized failures; stdout remains empty on failure.
19pub async fn run(
20    args: &CliArgs,
21    bootstrap: &CliBootstrap,
22    input: &mut dyn Read,
23    stdin_is_terminal: bool,
24    output: &mut dyn Write,
25    diagnostics: &mut dyn Write,
26) -> Result<(), CliFailure> {
27    if !args.print && stdin_is_terminal {
28        return Err(CliFailure::usage(
29            "print mode requires --print or piped stdin",
30        ));
31    }
32    let prompt = initial_prompt(args, input, stdin_is_terminal, bootstrap)?;
33    let (service, selection) = bootstrap.build_async(args).await?;
34    let result = run_service(&service, selection, &prompt, output, diagnostics).await;
35    service.shutdown().await;
36    result
37}
38
39async fn run_service(
40    service: &CodingAgentService,
41    selection: SessionSelection,
42    prompt: &str,
43    output: &mut dyn Write,
44    diagnostics: &mut dyn Write,
45) -> Result<(), CliFailure> {
46    let session_id = select_session(service, selection).await?;
47    let events = service.subscribe(session_id).map_err(CliFailure::from)?;
48    service
49        .prompt(session_id, prompt)
50        .map_err(CliFailure::from)?;
51    let event_task = tokio::spawn(drain_events(events));
52    let outcome = tokio::select! {
53        outcome = service.wait(session_id) => outcome.map_err(CliFailure::from),
54        signal = tokio::signal::ctrl_c() => {
55            match signal {
56                Ok(()) => Err(CliFailure::new(ExitCategory::Cancelled, "operation cancelled")),
57                Err(_) => Err(CliFailure::new(ExitCategory::Internal, "cancellation handler failed")),
58            }
59        }
60    };
61    event_task.abort();
62    let _ = event_task.await;
63    let outcome = outcome?;
64    let RuntimeCommandOutcome::RunCompleted {
65        session,
66        pending_approval_id,
67        ..
68    } = outcome
69    else {
70        return Err(CliFailure::new(
71            ExitCategory::Internal,
72            "prompt returned an unexpected outcome",
73        ));
74    };
75    if pending_approval_id.is_some() {
76        return Err(CliFailure::new(
77            ExitCategory::PolicyDenied,
78            "approval is required in non-interactive print mode",
79        ));
80    }
81    let text = final_assistant_text(session.messages()).ok_or_else(|| {
82        CliFailure::new(
83            ExitCategory::Provider,
84            "provider returned no final assistant text",
85        )
86    })?;
87    if text
88        .chars()
89        .any(|character| character.is_control() && !matches!(character, '\n' | '\t'))
90    {
91        return Err(CliFailure::new(
92            ExitCategory::Provider,
93            "provider returned unsafe terminal control text",
94        ));
95    }
96    output
97        .write_all(text.as_bytes())
98        .and_then(|()| {
99            if text.ends_with('\n') {
100                Ok(())
101            } else {
102                output.write_all(b"\n")
103            }
104        })
105        .and_then(|()| output.flush())
106        .map_err(|_| CliFailure::new(ExitCategory::Internal, "stdout write failed"))?;
107    if !service.resources().diagnostics().is_empty() {
108        diagnostics
109            .write_all(b"tea: optional workspace context was skipped\n")
110            .map_err(|_| CliFailure::new(ExitCategory::Internal, "stderr write failed"))?;
111    }
112    Ok(())
113}
114
115pub(crate) async fn select_session(
116    service: &CodingAgentService,
117    selection: SessionSelection,
118) -> Result<SessionId, CliFailure> {
119    match selection {
120        SessionSelection::New | SessionSelection::NoSession => {
121            service.create_session().await.map_err(CliFailure::from)
122        }
123        SessionSelection::Existing(session_id) => {
124            service
125                .open_session(session_id)
126                .await
127                .map_err(CliFailure::from)?;
128            Ok(session_id)
129        }
130        SessionSelection::Continue => {
131            let session_id = service
132                .list_sessions()
133                .await
134                .map_err(CliFailure::from)?
135                .first()
136                .map(tea_session::SessionCatalogEntry::session_id)
137                .ok_or_else(|| {
138                    CliFailure::new(ExitCategory::TrustOrConfig, "no session is available")
139                })?;
140            service
141                .open_session(session_id)
142                .await
143                .map_err(CliFailure::from)?;
144            Ok(session_id)
145        }
146    }
147}
148
149pub(crate) fn initial_prompt(
150    args: &CliArgs,
151    input: &mut dyn Read,
152    stdin_is_terminal: bool,
153    bootstrap: &CliBootstrap,
154) -> Result<String, CliFailure> {
155    if args.prompt.len() > 128 {
156        return Err(CliFailure::usage("too many prompt arguments"));
157    }
158    let mut prompt = String::new();
159    for value in &args.prompt {
160        let part = if let Some(path) = value.strip_prefix('@') {
161            bootstrap.read_prompt_file(args, path)?
162        } else {
163            value.clone()
164        };
165        append_prompt_part(&mut prompt, &part)?;
166    }
167    if !stdin_is_terminal {
168        let remaining = MAX_INITIAL_PROMPT_BYTES.saturating_sub(prompt.len());
169        let mut bytes = Vec::new();
170        input
171            .take(
172                u64::try_from(remaining.saturating_add(1))
173                    .map_err(|_| CliFailure::usage("prompt size bound is unsupported"))?,
174            )
175            .read_to_end(&mut bytes)
176            .map_err(|_| CliFailure::usage("stdin could not be read"))?;
177        if bytes.len() > remaining {
178            return Err(CliFailure::usage("prompt exceeds input size limit"));
179        }
180        let stdin =
181            String::from_utf8(bytes).map_err(|_| CliFailure::usage("stdin is not valid UTF-8"))?;
182        append_prompt_part(&mut prompt, &stdin)?;
183    }
184    if prompt.is_empty() || prompt.contains('\0') {
185        return Err(CliFailure::usage("one bounded prompt is required"));
186    }
187    Ok(prompt)
188}
189
190fn append_prompt_part(prompt: &mut String, part: &str) -> Result<(), CliFailure> {
191    if part.is_empty() {
192        return Ok(());
193    }
194    let separator = usize::from(!prompt.is_empty());
195    if prompt
196        .len()
197        .checked_add(separator)
198        .and_then(|length| length.checked_add(part.len()))
199        .is_none_or(|length| length > MAX_INITIAL_PROMPT_BYTES)
200    {
201        return Err(CliFailure::usage("prompt exceeds input size limit"));
202    }
203    if separator == 1 {
204        prompt.push('\n');
205    }
206    prompt.push_str(part);
207    Ok(())
208}
209
210fn final_assistant_text(messages: &[CanonicalMessage]) -> Option<String> {
211    let CanonicalMessage::Assistant { content, .. } = messages.last()? else {
212        return None;
213    };
214    let text = content
215        .iter()
216        .filter_map(|block| match block {
217            ContentBlock::Text { text } => Some(text.as_str()),
218            ContentBlock::Thinking { .. }
219            | ContentBlock::Image { .. }
220            | ContentBlock::ToolCall { .. }
221            | ContentBlock::HostedTool { .. }
222            | ContentBlock::Citation { .. } => None,
223        })
224        .collect::<String>();
225    (!text.is_empty()).then_some(text)
226}
227
228async fn drain_events(mut events: mpsc::Receiver<tea_protocol::EventEnvelope>) {
229    while events.recv().await.is_some() {}
230}