Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(cli): `--output-format stream-json` for `jan cli agent run` (#8968)

Akarshan Biswasaebdc2fde678
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdx
index 14c9ffae2..48991c20d 100644
--- a/docs/src/pages/docs/agent/cli.mdx
+++ b/docs/src/pages/docs/agent/cli.mdx
@@ -89,7 +89,8 @@ jan cli agent run --safe "run the migration" # approve each step
| `--resume[=ID]` | Resume the most recent session, or one by id |
| `-c`, `--continue` | Resume the most recent session |
| `--provider`, `--api-key` | Credential overrides for this run |
-| `--output-format <FORMAT>` | `text` (default) streams the answer; `json` prints one result object |
+| `--output-format <FORMAT>` | `text` (default) streams the answer; `json` prints one result object; `stream-json` prints one JSON event per line |
+| `--input-format <FORMAT>` | `text` (default) ignores stdin; `stream-json` reads client messages while the run is in flight. Requires `--output-format stream-json` |
<Callout type="info">
`run` takes a positional task, so a space-separated `--resume ID` would swallow it. Write the value
@@ -148,6 +149,32 @@ had said before it broke as `result`:
The process exit code is unchanged: `0` on success, `1` on failure.
+#### Streaming JSON, in both directions
+
+`--output-format stream-json` prints one JSON object per line as the run proceeds -- assistant
+text, tool calls, tool results, permission requests -- and ends with the same `result` object
+`--output-format json` prints on its own.
+
+`--input-format stream-json` opens the other direction: newline-delimited messages read on stdin
+for the run's lifetime. It requires `--output-format stream-json`, because the client is the only
+thing that can answer a permission request and it needs to be reading them.
+
+| Message | Shape |
+| --- | --- |
+| Follow-up turn | `{"type":"user","text":"also check the tests"}` |
+| Permission answer | `{"type":"permission","request_id":"perm-1","decision":"allow_once"}` |
+| Stop the run | `{"type":"abort"}` |
+
+A follow-up joins the run at the next turn boundary. `decision` is `allow_once`, `allow_always`, or
+`deny`, and each `request_id` is answerable once. A line that parses as none of these is reported
+as an `input_error` record and skipped, so one bad line cannot end a healthy run.
+
+<Callout type="info">
+Closing stdin is not an abort -- the run finishes and still prints its `result`. But it does end the
+only thing that can approve a gated tool call, so any request still pending is denied, as is any
+that comes afterwards. Keep the pipe open for as long as you want a say.
+</Callout>
+
### `step`
Run a single turn. Useful when debugging a prompt or a tool.
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rs
index 79521ec28..dd696a6f6 100644
--- a/src-tauri/jan-cli/src/main.rs
+++ b/src-tauri/jan-cli/src/main.rs
@@ -13,6 +13,7 @@ use app_lib::core::agent::plugins::InstalledPlugin;
use app_lib::core::cli::mcp::{self, split_kv, McpServerEntry};
use app_lib::core::cli::providers::{load_provider_configs, ProviderOverrides};
use app_lib::core::cli::run_report::OutputFormat;
+use app_lib::core::cli::stream_input::InputFormat;
use app_lib::core::cli::{
cli_agent_config_list, cli_agent_config_path, cli_agent_config_set, cli_agent_config_unset,
cli_agent_run, cli_agent_status, cli_agent_step, cli_agent_ui, cli_delete_thread,
@@ -313,9 +314,16 @@ enum AgentCommands {
#[command(flatten)]
resume: ResumeRunArgs,
/// `text` streams the answer as it arrives; `json` prints one result
- /// object on stdout when the run finishes
+ /// object on stdout when the run finishes; `stream-json` prints one
+ /// JSON event per line as the run proceeds, ending with that object
#[arg(long, value_enum, default_value_t = OutputFormat::Text)]
output_format: OutputFormat,
+ /// `stream-json` reads newline-delimited `user`, `permission` and
+ /// `abort` messages on stdin while the run is in flight, and requires
+ /// `--output-format stream-json`; `text` (the default) does not read
+ /// stdin at all
+ #[arg(long, value_enum, default_value_t = InputFormat::Text)]
+ input_format: InputFormat,
},
/// Run a single turn (debugging)
Step {
@@ -732,6 +740,7 @@ async fn handle_agent(cmd: AgentCommands) {
sandbox,
resume,
output_format,
+ input_format,
} => {
cli_agent_run(
&project,
@@ -745,6 +754,7 @@ async fn handle_agent(cmd: AgentCommands) {
},
resume.into_target(),
output_format,
+ input_format,
)
.await
}
@@ -1111,6 +1121,42 @@ mod tests {
assert!(Cli::parse_from(["jan", "--safe"]).safe);
}
+ /// Parse `jan cli agent run <task> <extra...>` and pull out its input format.
+ fn parsed_input_format(extra: &[&str]) -> InputFormat {
+ let mut argv = vec!["jan", "cli", "agent", "run", "task"];
+ argv.extend_from_slice(extra);
+ match Cli::parse_from(argv).command {
+ Some(Commands::Cli {
+ cmd:
+ CliCommands::Agent {
+ cmd: AgentCommands::Run { input_format, .. },
+ },
+ }) => input_format,
+ _ => panic!("expected `cli agent run`"),
+ }
+ }
+
+ /// Reading stdin is opt-in: a run with no `--input-format` must not consume
+ /// a pipe the caller is using for something else.
+ #[test]
+ fn input_format_parses_and_defaults_to_text() {
+ assert_eq!(parsed_input_format(&[]), InputFormat::Text);
+ assert_eq!(
+ parsed_input_format(&["--input-format", "stream-json"]),
+ InputFormat::StreamJson
+ );
+ assert!(Cli::try_parse_from([
+ "jan",
+ "cli",
+ "agent",
+ "run",
+ "task",
+ "--input-format",
+ "yaml"
+ ])
+ .is_err());
+ }
+
/// Parse `jan cli agent run <task> <extra...>` and pull out its output format.
fn parsed_output_format(extra: &[&str]) -> OutputFormat {
let mut argv = vec!["jan", "cli", "agent", "run", "task"];
@@ -1133,6 +1179,10 @@ mod tests {
parsed_output_format(&["--output-format", "json"]),
OutputFormat::Json
);
+ assert_eq!(
+ parsed_output_format(&["--output-format", "stream-json"]),
+ OutputFormat::StreamJson
+ );
assert_eq!(
parsed_output_format(&["--output-format=text"]),
OutputFormat::Text
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index a272062d6..836f272af 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -15,6 +15,7 @@ mod path_refs;
pub mod run_report;
pub mod providers;
mod secret_input;
+pub mod stream_input;
pub mod telemetry;
pub mod terminal_setup;
pub mod tokamak;
@@ -472,11 +473,15 @@ use crate::core::agent::project::{
ensure_project, load_agent_config, permissions_from, set_model_in_agent_toml,
};
use crate::core::agent::r#loop::{
- run_orchestration_streamed, OrchestrationArgs, PermissionRegistry,
+ run_orchestration_steered, run_orchestration_streamed, OrchestrationArgs, PermissionRegistry,
+ SteeringRequest,
};
use tauri_plugin_agent_tools::workspace;
use crate::core::cli::providers::{load_provider_configs, ProviderOverrides};
-use crate::core::cli::run_report::{OutputFormat, RunReport};
+use crate::core::cli::run_report::{ndjson_line, OutputFormat, PermissionDecisionRecord, RunReport};
+use crate::core::cli::stream_input::{
+ parse_input_line, InputErrorRecord, InputFormat, InputMessage, StreamInput,
+};
use crate::core::mcp::models::McpSettings;
use std::collections::HashMap;
use std::io::Write as _;
@@ -654,8 +659,20 @@ pub async fn cli_agent_run(
flags: SessionFlags,
resume: Option<ResumeTarget>,
format: OutputFormat,
+ input_format: InputFormat,
) -> Result<(), String> {
- run_agent_loop(project, task, model, false, overrides, flags, resume, format).await
+ run_agent_loop(
+ project,
+ task,
+ model,
+ false,
+ overrides,
+ flags,
+ resume,
+ format,
+ input_format,
+ )
+ .await
}
/// Single-turn run for debugging: the one place a turn cap is still applied,
@@ -676,6 +693,7 @@ pub async fn cli_agent_step(
flags,
None,
OutputFormat::Text,
+ InputFormat::Text,
)
.await
}
@@ -1113,7 +1131,22 @@ async fn run_agent_loop(
flags: SessionFlags,
resume: Option<ResumeTarget>,
format: OutputFormat,
+ input_format: InputFormat,
) -> Result<(), String> {
+ // A duplex run switches off both of the CLI's own answer paths, so the
+ // client is the only thing that can resolve a permission request -- and it
+ // can only do that if it is being told the request ids. `text` prints them
+ // to stderr and `json` prints nothing at all until the run ends, so either
+ // pairing leaves a gated call unanswerable. Rejected rather than silently
+ // upgraded: a caller parsing plain text should not have the format changed
+ // under it.
+ if input_format.is_stream_json() && !format.is_stream_json() {
+ return Err(
+ "--input-format stream-json requires --output-format stream-json (the client answers \
+ permission requests, so it must be reading them)"
+ .to_string(),
+ );
+ }
let started = std::time::Instant::now();
let prepared = prepare_agent_run(
project,
@@ -1135,13 +1168,16 @@ async fn run_agent_loop(
} = match prepared {
Ok(prepared) => prepared,
Err(e) => {
- if format.is_json() {
- print_report(RunReport::setup_failure(&e).finish(
- None,
- "",
- started.elapsed().as_millis(),
- None,
- ));
+ if format.is_machine() {
+ print_report(
+ format,
+ RunReport::setup_failure(&e).finish(
+ None,
+ "",
+ started.elapsed().as_millis(),
+ None,
+ ),
+ );
}
return Err(e);
}
@@ -1172,6 +1208,16 @@ async fn run_agent_loop(
}
}
+ // The client on stdin, when there is one: it owns every permission decision
+ // and can steer or stop the run while it is in flight.
+ let input = input_format
+ .is_stream_json()
+ .then(|| Arc::new(StreamInput::default()));
+ let reader = input.as_ref().map(|input| {
+ spawn_input_reader(Arc::clone(input), Arc::clone(&permission_requests), format)
+ });
+ let client = input.clone();
+
let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();
// The report is folded in both formats from the same stream the printer
// reads, so the JSON envelope can never disagree with the text output.
@@ -1179,18 +1225,45 @@ async fn run_agent_loop(
let mut report = RunReport::default();
while let Some(ev) = rx.recv().await {
report.observe(&ev);
- if format.is_json() {
- resolve_permission_silently(ev, &permission_requests).await;
- } else {
- print_event(ev, &permission_requests).await;
+ // Asked per event, not once per run: the client owns the decision
+ // only while it is still reading. Once stdin has closed, the CLI
+ // takes its own path back, which on a pipe is an auto-deny.
+ let duplex = client.as_ref().is_some_and(|c| !c.client_gone());
+ match format {
+ OutputFormat::Text => print_event(ev, &permission_requests, duplex).await,
+ OutputFormat::Json => {
+ resolve_permission_silently(ev, &permission_requests, duplex).await;
+ }
+ OutputFormat::StreamJson => {
+ print_json_line(&ev);
+ if let Some((request_id, decision)) =
+ resolve_permission_silently(ev, &permission_requests, duplex).await
+ {
+ print_json_line(&PermissionDecisionRecord::new(&request_id, decision));
+ }
+ }
}
}
report
});
- let result = run_orchestration_streamed(&tx, &body, &args).await;
+ // `None` when the client aborted: the run produced no completion, but a
+ // deliberate stop is an outcome rather than a failure, so it is reported on
+ // the stream and the process still exits 0.
+ let outcome = match input.as_ref() {
+ Some(input) => run_steered(&tx, &body, &args, input).await,
+ None => Some(run_orchestration_streamed(&tx, &body, &args).await),
+ };
+ if let Some(reader) = reader {
+ reader.abort();
+ }
+ let aborted = outcome.is_none();
+ let result = outcome.unwrap_or_else(|| Err(ABORTED_BY_CLIENT.to_string()));
drop(tx);
let report = printer.await.unwrap_or_default();
+ if let Some(input) = input.as_ref() {
+ report_dropped_follow_ups(input, format);
+ }
// Write the turn back so the session stays continuable with --resume.
let PersistTarget {
@@ -1208,7 +1281,7 @@ async fn run_agent_loop(
}
match cli_save_thread(&agent_dir, thread_id.as_deref(), &model, &history, None) {
Ok(id) => {
- if !format.is_json() {
+ if !format.is_machine() {
eprintln!(
"\x1b[2m[session {} - resume with `jan --resume={}`]\x1b[0m",
short_id(&id),
@@ -1220,37 +1293,253 @@ async fn run_agent_loop(
Err(e) => eprintln!("(could not save session: {e})"),
}
}
- if format.is_json() {
- print_report(report.finish(
- session_id.as_deref().map(short_id).as_deref(),
- &model,
- started.elapsed().as_millis(),
- final_text.as_deref(),
- ));
+ if format.is_machine() {
+ print_report(
+ format,
+ report.finish(
+ session_id.as_deref().map(short_id).as_deref(),
+ &model,
+ started.elapsed().as_millis(),
+ final_text.as_deref(),
+ ),
+ );
}
// The one-shot CLI runs exactly one turn, so its session ends here: wipe
// the persistent bash `/tmp` scratch this run used.
if let Some(session) = args.session_id.as_deref() {
let _ = workspace::remove_scratch_dir(session).await;
}
+ if aborted {
+ return Ok(());
+ }
result.map(|_| ())
}
-/// Write the result envelope to stdout, the only thing `--output-format json`
-/// puts there. Pretty-printed: these are read by people at least as often as by
-/// programs, and `jq` does not care either way.
-fn print_report(report: run_report::RunResult) {
- println!(
- "{}",
- serde_json::to_string_pretty(&report).unwrap_or_default()
- );
+/// Stop reason reported for a run the client ended with an `abort` message, and
+/// the error the run itself returns -- never printed, since an abort exits 0.
+const ABORTED_BY_CLIENT: &str = "aborted by client";
+
+/// Drive the run against a duplex client: the orchestration loop's steering
+/// handshake is answered from the queue the reader fills, and an `abort`
+/// message drops the run. `None` is that abort.
+///
+/// Dropping the orchestration future is what stops the run, so anything it was
+/// awaiting (an upstream request, a tool) is cancelled where it stands; a child
+/// process a `bash` call had already spawned outlives it, as it does on the
+/// TUI's cancel path.
+async fn run_steered(
+ tx: &mpsc::UnboundedSender<StreamEvent>,
+ body: &serde_json::Value,
+ args: &OrchestrationArgs,
+ input: &Arc<StreamInput>,
+) -> Option<Result<serde_json::Value, String>> {
+ let (steering_tx, mut steering_rx) = mpsc::unbounded_channel::<SteeringRequest>();
+ let queue = Arc::clone(input);
+ let steerer = tokio::spawn(async move {
+ while let Some(request) = steering_rx.recv().await {
+ // Empty is the normal answer: the loop asks at every turn boundary.
+ let _ = request.reply.send(queue.take_queued());
+ }
+ });
+ let outcome = tokio::select! {
+ result = run_orchestration_steered(tx, body, args, Some(&steering_tx)) => Some(result),
+ _ = input.aborted() => {
+ // The loop emits its own terminal event; an abort pre-empts it, so
+ // the report is given one here or it would read as a clean stop.
+ let _ = tx.send(StreamEvent::Done {
+ stop_reason: "aborted".to_string(),
+ usage: None,
+ });
+ None
+ }
+ };
+ steerer.abort();
+ outcome
+}
+
+/// What a client line asks the reader to do next.
+#[derive(Debug, PartialEq, Eq)]
+enum InputFlow {
+ Continue,
+ /// A permission request was answered; the id and decision are echoed on the
+ /// stream so it stays a complete account of the run.
+ Decided(String, PermissionDecision),
+ /// An `abort`: stop reading, the run is ending.
+ Stop,
+}
+
+/// Apply one client line. `Err` is the message reported back to the client; it
+/// is never fatal, since this is a peer process's output and one malformed line
+/// must not cost the work already done.
+async fn apply_input_line(
+ line: &str,
+ input: &StreamInput,
+ registry: &PermissionRegistry,
+) -> Result<InputFlow, String> {
+ match parse_input_line(line)? {
+ InputMessage::User(text) => {
+ input.queue_user(text);
+ Ok(InputFlow::Continue)
+ }
+ InputMessage::Abort => {
+ input.abort();
+ Ok(InputFlow::Stop)
+ }
+ InputMessage::Permission {
+ request_id,
+ decision,
+ } => {
+ // Taking the sender is what makes a decision single-use: a second
+ // reply for the same id finds nothing and is reported, rather than
+ // silently overwriting an answer the run already acted on.
+ let sender = registry.lock().await.remove(&request_id);
+ let Some(sender) = sender else {
+ return Err(format!("no permission request '{request_id}' is pending"));
+ };
+ let _ = sender.send(decision);
+ Ok(InputFlow::Decided(request_id, decision))
+ }
+ }
+}
+
+/// Client lines, read on a detached OS thread.
+///
+/// Not `tokio::io::stdin`: that parks the read on the runtime's blocking pool,
+/// which shutdown waits for, so a client that keeps stdin open -- which is what
+/// a duplex client does for the whole run -- leaves the process alive after its
+/// terminal record has been printed. A plain thread dies with the process.
+fn stdin_lines() -> mpsc::UnboundedReceiver<String> {
+ let (tx, rx) = mpsc::unbounded_channel();
+ std::thread::spawn(move || {
+ use std::io::BufRead as _;
+ for line in std::io::stdin().lock().lines().map_while(Result::ok) {
+ if tx.send(line).is_err() {
+ return;
+ }
+ }
+ });
+ rx
}
-/// Answer a permission request without printing progress, for the JSON format.
-/// Leaving it unanswered would wedge the run: the loop waits on the reply.
-/// Every other event is silent -- stdout belongs to the envelope.
-async fn resolve_permission_silently(ev: StreamEvent, registry: &PermissionRegistry) {
- if let StreamEvent::PermissionRequest {
+/// Consume client messages until `abort` or end of input.
+///
+/// End of input is not an abort: a client that has said everything it means to
+/// say may close the pipe and still want its answer. It *is* the end of the
+/// only thing that can answer a permission request, though, so the exit is
+/// latched and anything already waiting is released -- see
+/// [`strand_pending_permissions`].
+async fn read_input_lines(
+ mut lines: mpsc::UnboundedReceiver<String>,
+ input: Arc<StreamInput>,
+ registry: PermissionRegistry,
+ format: OutputFormat,
+) {
+ while let Some(line) = lines.recv().await {
+ if line.trim().is_empty() {
+ continue;
+ }
+ match apply_input_line(&line, &input, &registry).await {
+ Ok(InputFlow::Continue) => {}
+ Ok(InputFlow::Decided(request_id, decision)) => {
+ if format.is_stream_json() {
+ print_json_line(&PermissionDecisionRecord::new(&request_id, decision));
+ }
+ }
+ Ok(InputFlow::Stop) => break,
+ Err(message) => report_input_error(format, &message, &line),
+ }
+ }
+ // Latch first: a request raised between the drain and the latch would
+ // otherwise be recorded as the client's to answer and find no reader.
+ input.mark_client_gone();
+ strand_pending_permissions(&registry, format).await;
+}
+
+/// Name the follow-ups the run ended before reaching. Queued turns are joined
+/// at a turn boundary, so a run that stops first (abort, error, or an answer
+/// the model considered final) never consumes them; reported one by one, since
+/// the text is what the client needs to decide whether to send it again.
+fn report_dropped_follow_ups(input: &StreamInput, format: OutputFormat) {
+ for turn in input.take_queued() {
+ let text = turn["content"].as_str().unwrap_or_default().to_string();
+ report_input_error(format, "run ended before this follow-up was read", &text);
+ }
+}
+
+/// Release every request still waiting on a client that has gone. Dropping the
+/// sender is what resolves the run's `rx.await` to `Deny`, so the run declines
+/// the call and finishes with its result envelope rather than parking forever.
+/// The decision is echoed for the same reason a client-sent one is: the stream
+/// stays a complete account of what the run did.
+async fn strand_pending_permissions(registry: &PermissionRegistry, format: OutputFormat) {
+ let stranded: Vec<String> = registry.lock().await.drain().map(|(id, _)| id).collect();
+ for request_id in stranded {
+ if format.is_stream_json() {
+ print_json_line(&PermissionDecisionRecord::new(
+ &request_id,
+ PermissionDecision::Deny,
+ ));
+ } else {
+ eprintln!(
+ "\x1b[33m[permission] auto-denied '{request_id}' (client closed stdin)\x1b[0m"
+ );
+ }
+ }
+}
+
+fn spawn_input_reader(
+ input: Arc<StreamInput>,
+ registry: PermissionRegistry,
+ format: OutputFormat,
+) -> tokio::task::JoinHandle<()> {
+ tokio::spawn(read_input_lines(stdin_lines(), input, registry, format))
+}
+
+/// Tell the client its line was rejected, on whichever stream it is reading.
+fn report_input_error(format: OutputFormat, message: &str, line: &str) {
+ if format.is_stream_json() {
+ print_json_line(&InputErrorRecord::new(message, line));
+ } else {
+ eprintln!("\x1b[33m[input] {message}\x1b[0m");
+ }
+}
+
+/// Write the result envelope to stdout, the last thing either machine format
+/// puts there. `json` pretty-prints it -- those are read by people at least as
+/// often as by programs, and `jq` does not care either way -- while
+/// `stream-json` must keep it to the one line its contract promises.
+fn print_report(format: OutputFormat, report: run_report::RunResult) {
+ if format.is_stream_json() {
+ print_json_line(&report);
+ } else {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&report).unwrap_or_default()
+ );
+ }
+}
+
+/// Write one NDJSON record and flush it, so a consumer reading the pipe sees
+/// the event as it happens rather than when the block buffer fills.
+fn print_json_line<T: serde::Serialize>(value: &T) {
+ let Some(line) = ndjson_line(value) else {
+ return;
+ };
+ let mut out = std::io::stdout().lock();
+ let _ = out.write_all(line.as_bytes());
+ let _ = out.flush();
+}
+
+/// Answer a permission request without printing progress, for the machine
+/// formats. Leaving it unanswered would wedge the run: the loop waits on the
+/// reply. Returns the decision so `stream-json` can report it; with no TTY
+/// `prompt_permission` denies rather than blocking on a terminal nobody is at.
+async fn resolve_permission_silently(
+ ev: StreamEvent,
+ registry: &PermissionRegistry,
+ duplex: bool,
+) -> Option<(String, PermissionDecision)> {
+ let StreamEvent::PermissionRequest {
request_id,
tool_name,
capability,
@@ -1258,16 +1547,23 @@ async fn resolve_permission_silently(ev: StreamEvent, registry: &PermissionRegis
command,
..
} = ev
- {
- let detail = command
- .map(|c| format!(" ({c})"))
- .or_else(|| path.map(|p| format!(" on {p}")))
- .unwrap_or_default();
- let decision = prompt_permission(tool_name, capability, detail).await;
- if let Some(sender) = registry.lock().await.remove(&request_id) {
- let _ = sender.send(decision);
- }
+ else {
+ return None;
+ };
+ // With a client on stdin the decision is its call; answering here would
+ // race the reply already on its way.
+ if duplex {
+ return None;
}
+ let detail = command
+ .map(|c| format!(" ({c})"))
+ .or_else(|| path.map(|p| format!(" on {p}")))
+ .unwrap_or_default();
+ let decision = prompt_permission(tool_name, capability, detail).await;
+ if let Some(sender) = registry.lock().await.remove(&request_id) {
+ let _ = sender.send(decision);
+ }
+ Some((request_id, decision))
}
/// Assistant text of a chat-completion response, if any.
@@ -1327,7 +1623,7 @@ pub fn agent_dir_for(project_root: &std::path::Path) -> PathBuf {
/// Render one `StreamEvent` for the terminal. Content tokens go to stdout so a
/// run can be piped; progress/diagnostics go to stderr. `PermissionRequest` is
/// resolved via the terminal (deny when non-interactive).
-async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {
+async fn print_event(ev: StreamEvent, registry: &PermissionRegistry, duplex: bool) {
if crate::core::cli::auth::account::take_claude_alias_engaged() {
eprintln!(
"\x1b[33m[warning] {}\x1b[0m",
@@ -1447,6 +1743,12 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {
if let Some(diff) = diff {
eprintln!("\x1b[2m{diff}\x1b[0m");
}
+ if duplex {
+ eprintln!(
+ "\x1b[33m[permission] {capability} via '{tool_name}'{detail} - awaiting '{request_id}' on stdin\x1b[0m"
+ );
+ return;
+ }
let decision = prompt_permission(tool_name, capability, detail).await;
if let Some(sender) = registry.lock().await.remove(&request_id) {
let _ = sender.send(decision);
@@ -1488,6 +1790,161 @@ async fn prompt_permission(
mod tests {
use super::*;
+ /// The duplex channel end to end over a pipe: a follow-up is queued for the
+ /// steering handshake, a permission reply reaches the waiting run, a
+ /// malformed line is survivable, and `abort` stops the reader.
+ ///
+ /// Driven through `read_input_lines` rather than the built binary because a
+ /// cargo test cannot own process stdin; the binary is exercised by hand.
+ #[tokio::test]
+ async fn a_duplex_client_steers_answers_and_aborts_over_one_pipe() {
+ let input = Arc::new(StreamInput::default());
+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ let (answer_tx, answer) = tokio::sync::oneshot::channel();
+ registry.lock().await.insert("perm-1".to_string(), answer_tx);
+
+ let script = [
+ r#"{"type":"user","text":"also check the tests"}"#,
+ " ",
+ "{ not json",
+ r#"{"type":"permission","request_id":"perm-1","decision":"allow_once"}"#,
+ r#"{"type":"user","text":"and the docs"}"#,
+ r#"{"type":"abort"}"#,
+ r#"{"type":"user","text":"never read"}"#,
+ ];
+ let (lines_tx, lines) = mpsc::unbounded_channel();
+ for line in script {
+ lines_tx.send(line.to_string()).expect("reader is alive");
+ }
+ drop(lines_tx);
+ read_input_lines(
+ lines,
+ Arc::clone(&input),
+ Arc::clone(&registry),
+ OutputFormat::Json,
+ )
+ .await;
+
+ assert_eq!(
+ answer.await.expect("the run's permission wait is answered"),
+ PermissionDecision::AllowOnce
+ );
+ let queued = input.take_queued();
+ assert_eq!(queued.len(), 2, "the bad line cost neither follow-up");
+ assert_eq!(queued[0]["content"], "also check the tests");
+ assert_eq!(queued[1]["content"], "and the docs");
+ // Lines after `abort` are not read: the run is already ending.
+ assert!(input.take_queued().is_empty());
+ input.aborted().await;
+ }
+
+ /// A decision is single-use. The second reply has no sender left to take,
+ /// which is what keeps a client from answering a request the run already
+ /// acted on.
+ #[tokio::test]
+ async fn a_second_reply_to_one_request_is_rejected() {
+ let input = StreamInput::default();
+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ let (tx, _rx) = tokio::sync::oneshot::channel();
+ registry.lock().await.insert("perm-1".to_string(), tx);
+ let line = r#"{"type":"permission","request_id":"perm-1","decision":"deny"}"#;
+
+ assert_eq!(
+ apply_input_line(line, &input, &registry).await,
+ Ok(InputFlow::Decided(
+ "perm-1".to_string(),
+ PermissionDecision::Deny
+ ))
+ );
+ let err = apply_input_line(line, &input, &registry)
+ .await
+ .expect_err("nothing is pending any more");
+ assert!(err.contains("no permission request 'perm-1'"), "{err}");
+ }
+
+ /// The wedge this guards: with a client on stdin the CLI answers nothing
+ /// itself, so a request still pending when the pipe closes had no way out.
+ /// Dropping the sender is what resolves the run's wait to `Deny`.
+ #[tokio::test]
+ async fn closing_stdin_releases_a_request_the_client_never_answered() {
+ let input = Arc::new(StreamInput::default());
+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ let (answer_tx, answer) = tokio::sync::oneshot::channel();
+ registry
+ .lock()
+ .await
+ .insert("perm-1".to_string(), answer_tx);
+
+ // No lines at all: the client opened the pipe and closed it again.
+ let (lines_tx, lines) = mpsc::unbounded_channel::<String>();
+ drop(lines_tx);
+ read_input_lines(
+ lines,
+ Arc::clone(&input),
+ Arc::clone(&registry),
+ OutputFormat::StreamJson,
+ )
+ .await;
+
+ assert!(
+ answer.await.is_err(),
+ "the sender is dropped, which the run reads as Deny"
+ );
+ assert!(registry.lock().await.is_empty());
+ assert!(
+ input.client_gone(),
+ "later requests must not be recorded as the client's to answer"
+ );
+ }
+
+ /// The other half of the same wedge: a request raised *after* the pipe
+ /// closed. The latch is what sends the printer back to its own answer path.
+ #[tokio::test]
+ async fn a_request_raised_after_the_client_left_is_not_left_to_the_client() {
+ let input = StreamInput::default();
+ assert!(!input.client_gone());
+ input.mark_client_gone();
+ assert!(input.client_gone());
+ }
+
+ /// `--input-format stream-json` with any other output format leaves the
+ /// client unable to see the request ids it is expected to answer.
+ #[tokio::test]
+ async fn a_duplex_run_is_refused_unless_the_output_is_stream_json() {
+ for format in [OutputFormat::Text, OutputFormat::Json] {
+ let err = run_agent_loop(
+ ".",
+ "task",
+ None,
+ false,
+ ProviderOverrides::default(),
+ SessionFlags::default(),
+ None,
+ format,
+ InputFormat::StreamJson,
+ )
+ .await
+ .expect_err("the pairing is required");
+ assert!(
+ err.contains("requires --output-format stream-json"),
+ "{err}"
+ );
+ }
+ }
+
+ /// A queued follow-up the run never reached is reported rather than
+ /// vanishing, so the client knows to send it again.
+ #[test]
+ fn follow_ups_the_run_never_read_are_reported() {
+ let input = StreamInput::default();
+ input.queue_user("and the docs".to_string());
+ report_dropped_follow_ups(&input, OutputFormat::StreamJson);
+ assert!(
+ input.take_queued().is_empty(),
+ "reporting drains, so a second call cannot double-report"
+ );
+ }
+
/// Signing in to Tokamak is what unlocks the desktop inherit. Without it the
/// model stays unset so the TUI's sign-in notice fires, instead of the
/// session silently starting on whatever the desktop app last had selected.
diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rs
index ef3947673..8f0504e43 100644
--- a/src-tauri/src/core/cli/run_report.rs
+++ b/src-tauri/src/core/cli/run_report.rs
@@ -5,8 +5,26 @@
//! is over, so a caller can branch on `is_error` and read `result` without
//! parsing terminal chatter. The object is assembled from the same
//! [`StreamEvent`]s the printer consumes -- there is no second source of truth.
+//!
+//! `--output-format stream-json` is the same envelope preceded by the trace:
+//! one JSON object per line on stdout, flushed as each event is produced, with
+//! the envelope as the last line. The wire shape of a trace line is
+//! [`StreamEvent`]'s own `#[serde(tag = "type")]` serialization, so the tags a
+//! consumer matches on are the snake_case variant names: `token`, `reasoning`,
+//! `step`, `tool_call_started`, `tool_call_args_delta`, `tool_call`,
+//! `tool_output_delta`, `tool_result`, `subagent_start`, `subagent_queued`,
+//! `subagent_end`, `subagent_plan`, `subagent`, `notice`, `monitors`,
+//! `parked`, `messages_updated`, `ask_request`, `ask_resolved`, `todo_update`,
+//! `turn_usage`, `done`, `error`, `permission_request`. Two tags are minted
+//! here rather than by the loop: `permission_decision` (how this CLI answered a
+//! `permission_request`) and the terminal `result`.
+//!
+//! `monitors`, `parked` and `notice` are display-only progress; a consumer that
+//! only wants the outcome can read the last line alone. Unknown tags must be
+//! ignored rather than treated as an error -- new variants are additive.
use crate::core::agent::events::StreamEvent;
+use tauri_plugin_agent_tools::tools::gate::PermissionDecision;
/// How a non-interactive run reports itself.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
@@ -16,11 +34,54 @@ pub enum OutputFormat {
Text,
/// A single result object on stdout when the run finishes.
Json,
+ /// One NDJSON record per event on stdout, terminated by the result object.
+ StreamJson,
}
impl OutputFormat {
- pub(crate) fn is_json(self) -> bool {
- matches!(self, OutputFormat::Json)
+ /// Stdout belongs to a program rather than a person: no prose, no spinner,
+ /// and the result envelope is printed even when the run failed at setup.
+ pub(crate) fn is_machine(self) -> bool {
+ matches!(self, OutputFormat::Json | OutputFormat::StreamJson)
+ }
+
+ pub(crate) fn is_stream_json(self) -> bool {
+ matches!(self, OutputFormat::StreamJson)
+ }
+}
+
+/// One NDJSON record: the compact serialization plus its terminating newline.
+/// Serialization of a `StreamEvent` is infallible in practice; an encoding
+/// failure yields no line rather than a truncated one a consumer would choke on.
+pub(crate) fn ndjson_line<T: serde::Serialize>(value: &T) -> Option<String> {
+ serde_json::to_string(value).ok().map(|mut s| {
+ s.push('\n');
+ s
+ })
+}
+
+/// How the CLI answered a [`StreamEvent::PermissionRequest`]. The loop does not
+/// emit this: the decision is made here, and without it a piped consumer sees
+/// the request and never learns that the run was denied.
+#[derive(serde::Serialize)]
+pub(crate) struct PermissionDecisionRecord<'a> {
+ #[serde(rename = "type")]
+ kind: &'static str,
+ request_id: &'a str,
+ decision: &'static str,
+}
+
+impl<'a> PermissionDecisionRecord<'a> {
+ pub(crate) fn new(request_id: &'a str, decision: PermissionDecision) -> Self {
+ Self {
+ kind: "permission_decision",
+ request_id,
+ decision: match decision {
+ PermissionDecision::AllowOnce => "allow_once",
+ PermissionDecision::AllowAlways => "allow_always",
+ PermissionDecision::Deny => "deny",
+ },
+ }
}
}
@@ -350,6 +411,65 @@ mod tests {
}
}
+ /// The stream-json contract: every record is independently parseable on its
+ /// own line, carries a `type` tag, and the envelope is the last one.
+ #[test]
+ fn the_ndjson_stream_parses_line_by_line_and_ends_with_the_result() {
+ let events = [
+ StreamEvent::Step { index: 1, max: 0 },
+ StreamEvent::ToolCall {
+ id: "call_1".to_string(),
+ name: "bash".to_string(),
+ args: serde_json::json!({ "command": "echo \"hi\"\nls" }),
+ },
+ token("done\nand done"),
+ StreamEvent::Done {
+ stop_reason: "end_turn".to_string(),
+ usage: None,
+ },
+ ];
+ let mut report = RunReport::default();
+ let mut stream = String::new();
+ for ev in &events {
+ report.observe(ev);
+ stream.push_str(&ndjson_line(ev).unwrap());
+ }
+ stream.push_str(
+ &ndjson_line(&PermissionDecisionRecord::new(
+ "perm-1",
+ PermissionDecision::Deny,
+ ))
+ .unwrap(),
+ );
+ stream.push_str(&ndjson_line(&report.finish(None, "m", 1, Some("done\nand done"))).unwrap());
+
+ assert!(stream.ends_with('\n'));
+ let lines: Vec<&str> = stream.lines().collect();
+ assert_eq!(lines.len(), events.len() + 2);
+ let parsed: Vec<serde_json::Value> = lines
+ .iter()
+ .map(|line| serde_json::from_str(line).expect("each line parses on its own"))
+ .collect();
+ let tags: Vec<&str> = parsed
+ .iter()
+ .map(|v| v["type"].as_str().expect("every record is tagged"))
+ .collect();
+ assert_eq!(
+ tags,
+ [
+ "step",
+ "tool_call",
+ "token",
+ "done",
+ "permission_decision",
+ "result"
+ ]
+ );
+ assert_eq!(parsed[4]["decision"], "deny");
+ assert_eq!(parsed[4]["request_id"], "perm-1");
+ assert_eq!(parsed[5]["result"], "done\nand done");
+ }
+
#[test]
fn context_overflow_is_classified_from_the_marker() {
let mut report = RunReport::default();
diff --git a/src-tauri/src/core/cli/stream_input.rs b/src-tauri/src/core/cli/stream_input.rs
new file mode 100644
index 000000000..b0c83135b
--- /dev/null
+++ b/src-tauri/src/core/cli/stream_input.rs
@@ -0,0 +1,252 @@
+//! The input half of the headless stream-json channel: newline-delimited JSON
+//! read from stdin while a run is in flight.
+//!
+//! `--output-format stream-json` (see [`super::run_report`]) made a run
+//! readable by a program. On its own that is a one-way mirror: the task is
+//! baked into a single string before the process starts, a gated tool call can
+//! only be denied because piped stdin has no terminal to ask, and the only way
+//! to stop the run is to kill it. This module is the reply path -- the same
+//! `{"type": ...}` framing in the other direction.
+//!
+//! Three kinds, matching the three things a caller cannot say today:
+//! `user` (a follow-up joined to the run in flight at the next turn boundary,
+//! via the orchestration loop's existing steering handshake), `abort`, and
+//! `permission` (a decision keyed to a `permission_request` already on stdout).
+//! A line that parses as none of them is reported as an `input_error` record
+//! and skipped: the reader is a peer process's output, so one bad line must not
+//! be able to end a run that is otherwise healthy.
+
+use std::collections::VecDeque;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Mutex;
+use tauri_plugin_agent_tools::tools::gate::PermissionDecision;
+use tokio::sync::Notify;
+
+/// How a non-interactive run is spoken to.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
+pub enum InputFormat {
+ /// The positional task is the whole conversation; stdin is not read.
+ #[default]
+ Text,
+ /// Newline-delimited JSON messages on stdin, read for the run's lifetime.
+ StreamJson,
+}
+
+impl InputFormat {
+ pub(crate) fn is_stream_json(self) -> bool {
+ matches!(self, InputFormat::StreamJson)
+ }
+}
+
+/// One well-formed line from the client.
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) enum InputMessage {
+ /// A follow-up turn for the run in flight.
+ User(String),
+ /// Stop the run; the terminal envelope still reports what it had produced.
+ Abort,
+ /// The answer to a `permission_request` this run emitted.
+ Permission {
+ request_id: String,
+ decision: PermissionDecision,
+ },
+}
+
+/// Parse one NDJSON line. The error is what the client is told on the stream,
+/// so it names the offending value rather than just the expected shape.
+pub(crate) fn parse_input_line(line: &str) -> Result<InputMessage, String> {
+ let value: serde_json::Value =
+ serde_json::from_str(line).map_err(|e| format!("not JSON: {e}"))?;
+ let Some(kind) = value.get("type").and_then(|v| v.as_str()) else {
+ return Err("missing string field 'type'".to_string());
+ };
+ match kind {
+ "user" => {
+ let text = value
+ .get("text")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "'user' needs a string field 'text'".to_string())?;
+ if text.trim().is_empty() {
+ return Err("'user' text is empty".to_string());
+ }
+ Ok(InputMessage::User(text.to_string()))
+ }
+ "abort" => Ok(InputMessage::Abort),
+ "permission" => {
+ let request_id = value
+ .get("request_id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "'permission' needs a string field 'request_id'".to_string())?;
+ let decision = value
+ .get("decision")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "'permission' needs a string field 'decision'".to_string())?;
+ let decision = match decision {
+ "allow_once" => PermissionDecision::AllowOnce,
+ "allow_always" => PermissionDecision::AllowAlways,
+ "deny" => PermissionDecision::Deny,
+ other => {
+ return Err(format!(
+ "unknown decision '{other}' (allow_once, allow_always, deny)"
+ ))
+ }
+ };
+ Ok(InputMessage::Permission {
+ request_id: request_id.to_string(),
+ decision,
+ })
+ }
+ other => Err(format!("unknown type '{other}' (user, abort, permission)")),
+ }
+}
+
+/// A rejected input line, reported on stdout. Deliberately *not* a
+/// [`StreamEvent::Error`](crate::core::agent::events::StreamEvent::Error): the
+/// report folds that into the run's outcome, so a typo in one line would mark
+/// an otherwise successful run as failed.
+#[derive(serde::Serialize)]
+pub(crate) struct InputErrorRecord<'a> {
+ #[serde(rename = "type")]
+ kind: &'static str,
+ message: &'a str,
+ /// The line that was rejected, so the client can match it to what it wrote.
+ line: &'a str,
+}
+
+impl<'a> InputErrorRecord<'a> {
+ pub(crate) fn new(message: &'a str, line: &'a str) -> Self {
+ Self {
+ kind: "input_error",
+ message,
+ line,
+ }
+ }
+}
+
+/// What the reader task and the run share: the queue the steering handshake
+/// drains, and the abort latch the run selects on.
+#[derive(Default)]
+pub(crate) struct StreamInput {
+ queued: Mutex<VecDeque<serde_json::Value>>,
+ aborted: AtomicBool,
+ abort: Notify,
+ gone: AtomicBool,
+}
+
+impl StreamInput {
+ pub(crate) fn queue_user(&self, text: String) {
+ self.lock()
+ .push_back(serde_json::json!({ "role": "user", "content": text }));
+ }
+
+ /// Hand the queue to a steering handshake. Empty is the normal answer: the
+ /// loop asks at every turn boundary whether anything is waiting.
+ pub(crate) fn take_queued(&self) -> Vec<serde_json::Value> {
+ self.lock().drain(..).collect()
+ }
+
+ /// A std mutex is enough because nothing awaits while it is held, and it
+ /// keeps `queue_user` callable from the reader without an await point.
+ fn lock(&self) -> std::sync::MutexGuard<'_, VecDeque<serde_json::Value>> {
+ self.queued.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ /// The reader has stopped, so nothing on stdin can answer a permission
+ /// request any more. Latched rather than signalled: the question is asked
+ /// once per request, at whatever point in the run it arrives.
+ pub(crate) fn mark_client_gone(&self) {
+ self.gone.store(true, Ordering::SeqCst);
+ }
+
+ pub(crate) fn client_gone(&self) -> bool {
+ self.gone.load(Ordering::SeqCst)
+ }
+
+ pub(crate) fn abort(&self) {
+ self.aborted.store(true, Ordering::SeqCst);
+ self.abort.notify_waiters();
+ }
+
+ /// Resolve once the client has asked to stop. Parks forever otherwise, so
+ /// it is safe as a `select!` arm for the whole run.
+ pub(crate) async fn aborted(&self) {
+ // The latch is checked first: an abort that arrived before this future
+ // was polled has already fired its notification and would be missed.
+ if self.aborted.load(Ordering::SeqCst) {
+ return;
+ }
+ self.abort.notified().await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_three_message_kinds_parse() {
+ assert_eq!(
+ parse_input_line(r#"{"type":"user","text":"also check the tests"}"#).unwrap(),
+ InputMessage::User("also check the tests".to_string())
+ );
+ assert_eq!(
+ parse_input_line(r#"{"type":"abort"}"#).unwrap(),
+ InputMessage::Abort
+ );
+ assert_eq!(
+ parse_input_line(
+ r#"{"type":"permission","request_id":"perm-1","decision":"allow_once"}"#
+ )
+ .unwrap(),
+ InputMessage::Permission {
+ request_id: "perm-1".to_string(),
+ decision: PermissionDecision::AllowOnce,
+ }
+ );
+ }
+
+ /// Every rejection names what was wrong: the client sees this text on the
+ /// stream and has nothing else to debug against.
+ #[test]
+ fn malformed_lines_are_rejected_with_a_reason() {
+ for (line, marker) in [
+ ("not json at all", "not JSON"),
+ (r#"{"text":"hi"}"#, "missing string field 'type'"),
+ (r#"{"type":"steer","text":"hi"}"#, "unknown type 'steer'"),
+ (r#"{"type":"user"}"#, "string field 'text'"),
+ (r#"{"type":"user","text":" "}"#, "is empty"),
+ (r#"{"type":"permission","decision":"deny"}"#, "'request_id'"),
+ (r#"{"type":"permission","request_id":"p"}"#, "'decision'"),
+ (
+ r#"{"type":"permission","request_id":"p","decision":"maybe"}"#,
+ "unknown decision 'maybe'",
+ ),
+ ] {
+ let err = parse_input_line(line).expect_err(line);
+ assert!(err.contains(marker), "{line}: {err} lacks {marker}");
+ }
+ }
+
+ #[test]
+ fn queued_turns_drain_once_and_in_order() {
+ let input = StreamInput::default();
+ assert!(input.take_queued().is_empty());
+ input.queue_user("first".to_string());
+ input.queue_user("second".to_string());
+ let drained = input.take_queued();
+ assert_eq!(drained.len(), 2);
+ assert_eq!(drained[0]["role"], "user");
+ assert_eq!(drained[0]["content"], "first");
+ assert_eq!(drained[1]["content"], "second");
+ assert!(input.take_queued().is_empty());
+ }
+
+ /// The latch, not just the notification: an abort landing before the run
+ /// parks on it must still be seen, or the client's stop is swallowed.
+ #[tokio::test]
+ async fn an_abort_that_arrives_early_is_still_observed() {
+ let input = StreamInput::default();
+ input.abort();
+ input.aborted().await;
+ }
+}