Skip to main content

tea_cli/modes/
json.rs

1use std::io::{Read, Write};
2
3use serde::Serialize;
4use tea::RuntimeCommandOutcome;
5use tea_coding::CodingAgentService;
6use tea_policy::WorkspaceId;
7use tea_protocol::{CURRENT_PROTOCOL_VERSION, ProtocolVersion, SessionId};
8
9use crate::args::{CliArgs, SessionSelection};
10use crate::jsonl::{JSON_WRITER_DEADLINE, JsonLineFailure, JsonLineWriter};
11use crate::{CliBootstrap, CliFailure, ExitCategory};
12
13const JSON_MODE_VERSION: &str = "1.0";
14
15#[derive(Debug, Serialize)]
16#[serde(rename_all = "camelCase")]
17struct JsonModeHeader<'a> {
18    #[serde(rename = "type")]
19    kind: &'static str,
20    mode_version: &'static str,
21    protocol_version: ProtocolVersion,
22    session_id: SessionId,
23    workspace_id: &'a WorkspaceId,
24}
25
26/// Runs canonical LF-delimited JSON event mode.
27///
28/// # Errors
29///
30/// Returns stable categorized failures. This mode writes only its versioned
31/// header and canonical event envelopes to stdout.
32pub async fn run(
33    args: &CliArgs,
34    bootstrap: &CliBootstrap,
35    input: &mut dyn Read,
36    stdin_is_terminal: bool,
37    output: Box<dyn Write + Send>,
38) -> Result<(), CliFailure> {
39    if !args.json {
40        return Err(CliFailure::usage("JSON event mode requires --json"));
41    }
42    let prompt = super::print::initial_prompt(args, input, stdin_is_terminal, bootstrap)?;
43    let (service, selection) = bootstrap.build_async(args).await?;
44    let result = run_service(&service, selection, &prompt, output).await;
45    service.shutdown().await;
46    result
47}
48
49async fn run_service(
50    service: &CodingAgentService,
51    selection: SessionSelection,
52    prompt: &str,
53    output: Box<dyn Write + Send>,
54) -> Result<(), CliFailure> {
55    let session_id = super::print::select_session(service, selection).await?;
56    let mut events = service.subscribe(session_id).map_err(CliFailure::from)?;
57    let writer = JsonLineWriter::spawn(output, JSON_WRITER_DEADLINE).map_err(writer_failure)?;
58    writer
59        .write(&JsonModeHeader {
60            kind: "tea_event_stream",
61            mode_version: JSON_MODE_VERSION,
62            protocol_version: CURRENT_PROTOCOL_VERSION,
63            session_id,
64            workspace_id: service.workspace_id(),
65        })
66        .await
67        .map_err(writer_failure)?;
68    service
69        .prompt(session_id, prompt)
70        .map_err(CliFailure::from)?;
71
72    let mut wait = Box::pin(service.wait(session_id));
73    let outcome = loop {
74        tokio::select! {
75            biased;
76            event = events.recv() => match event {
77                Some(event) => writer.write(&event).await.map_err(writer_failure)?,
78                None => {
79                    break wait.await.map_err(CliFailure::from);
80                }
81            },
82            outcome = &mut wait => break outcome.map_err(CliFailure::from),
83            signal = tokio::signal::ctrl_c() => {
84                break match signal {
85                    Ok(()) => Err(CliFailure::new(ExitCategory::Cancelled, "operation cancelled")),
86                    Err(_) => Err(CliFailure::new(ExitCategory::Internal, "cancellation handler failed")),
87                };
88            }
89        }
90    };
91
92    // Runtime emission is awaited before command completion, so every event
93    // already accepted for this run is now present in the bounded receiver.
94    while let Ok(event) = events.try_recv() {
95        writer.write(&event).await.map_err(writer_failure)?;
96    }
97    let outcome = outcome?;
98    let RuntimeCommandOutcome::RunCompleted {
99        pending_approval_id,
100        ..
101    } = outcome
102    else {
103        return Err(CliFailure::new(
104            ExitCategory::Internal,
105            "prompt returned an unexpected outcome",
106        ));
107    };
108    if pending_approval_id.is_some() {
109        return Err(CliFailure::new(
110            ExitCategory::PolicyDenied,
111            "approval is required in non-interactive JSON mode",
112        ));
113    }
114    Ok(())
115}
116
117fn writer_failure(error: JsonLineFailure) -> CliFailure {
118    match error {
119        JsonLineFailure::InvalidValue => {
120            CliFailure::new(ExitCategory::Internal, "JSON event serialization failed")
121        }
122        JsonLineFailure::Closed | JsonLineFailure::Deadline => {
123            CliFailure::new(ExitCategory::Cancelled, "JSON output is unavailable")
124        }
125    }
126}