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): freeze the headless protocol at v1 with an init record

thinhlpg9df6eaec0374
diff --git a/src-tauri/jan-cli/tests/stream_json_init.rs b/src-tauri/jan-cli/tests/stream_json_init.rs
new file mode 100644
index 000000000..e3de63a25
--- /dev/null
+++ b/src-tauri/jan-cli/tests/stream_json_init.rs
@@ -0,0 +1,316 @@
+//! The first line of a `stream-json` run is the `init` handshake -- for a run
+//! that succeeds and for one whose first request fails.
+//!
+//! Driven through the real binary on purpose. The guarantee is about what
+//! reaches stdout, and the printer writes to the process's own fd 1, which an
+//! in-process test harness does not capture; a unit test could only assert that
+//! the function is called before the run, not that nothing else got there
+//! first.
+//!
+//! The provider is a stub on a loopback port speaking SSE, so the run needs no
+//! credentials, no network, and no local engine.
+
+use std::io::{Read, Write};
+use std::net::{TcpListener, TcpStream};
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output, Stdio};
+use std::time::Duration;
+
+/// A healthy completion, as the OpenAI streaming shape the engine parses.
+const ANSWER: &str = concat!(
+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",
+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",",
+ "\"content\":\"stub answer\"},\"finish_reason\":null}]}\n\n",
+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",
+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],",
+ "\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2,\"total_tokens\":7}}\n\n",
+ "data: [DONE]\n\n",
+);
+
+/// What a request the provider refuses looks like. A 4xx is refused outright
+/// where a 5xx would be retried with backoff, which keeps this case as fast as
+/// the healthy one while exercising the same path.
+const REFUSAL: &str =
+ "{\"error\":{\"message\":\"stub refused the request\",\"type\":\"invalid_request_error\"}}";
+
+/// Serve one canned reply per connection until the test process exits, and
+/// return the OpenAI-compatible base URL for it.
+fn stub_provider(status: &'static str, content_type: &'static str, body: &'static str) -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind the stub provider");
+ let addr = listener.local_addr().expect("stub address");
+ std::thread::spawn(move || {
+ for stream in listener.incoming() {
+ let Ok(mut stream) = stream else { continue };
+ read_request(&mut stream);
+ let response = format!(
+ "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes());
+ let _ = stream.flush();
+ }
+ });
+ format!("http://{addr}/v1")
+}
+
+/// Read a request off the wire, headers and body. Without this the client sees
+/// a reset instead of an answer, which would make a failure case pass for the
+/// wrong reason.
+fn read_request(stream: &mut TcpStream) {
+ let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
+ let mut buf: Vec<u8> = Vec::new();
+ let mut chunk = [0u8; 4096];
+ loop {
+ match stream.read(&mut chunk) {
+ Ok(0) | Err(_) => return,
+ Ok(n) => buf.extend_from_slice(&chunk[..n]),
+ }
+ let Some(head) = buf.windows(4).position(|w| w == b"\r\n\r\n") else {
+ continue;
+ };
+ let headers = String::from_utf8_lossy(&buf[..head]).to_ascii_lowercase();
+ let want = headers
+ .lines()
+ .find_map(|line| line.strip_prefix("content-length:"))
+ .and_then(|v| v.trim().parse::<usize>().ok())
+ .unwrap_or(0);
+ if buf.len() >= head + 4 + want {
+ return;
+ }
+ }
+}
+
+/// A private home and data folder per test, removed by the caller. Not
+/// `tempfile`: this crate has no dev-dependency, and one is not worth adding
+/// for two directories.
+struct Scratch {
+ root: PathBuf,
+}
+
+impl Scratch {
+ fn new(name: &str) -> Self {
+ let root = std::env::temp_dir().join(format!("jan-init-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ std::fs::create_dir_all(&root).expect("scratch dir");
+ Self { root }
+ }
+
+ fn home(&self) -> PathBuf {
+ self.root.join("home")
+ }
+
+ fn project(&self) -> PathBuf {
+ self.root.join("project")
+ }
+
+ /// Register the stub as the one usable provider, through the CLI's own
+ /// config writer so this test cannot drift from the file format.
+ fn configure(&self, base_url: &str) {
+ let out = self
+ .command(&[
+ "config",
+ "set",
+ "--provider",
+ "stub",
+ "--api-key",
+ "test-key",
+ "--base-url",
+ base_url,
+ "--model",
+ "stub-model",
+ ])
+ .output()
+ .expect("run `jan config set`");
+ assert!(
+ out.status.success(),
+ "config set failed: {}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ }
+
+ /// Run `jan cli agent run` to completion, machine-readable, with stdin
+ /// closed. A `stream-json` reader that hits end of input is the ordinary
+ /// case: the run keeps going, it just has no client left to talk to.
+ fn run(&self) -> Output {
+ let project = self.project();
+ self.command(&[
+ "cli",
+ "agent",
+ "run",
+ "--project",
+ project.to_str().expect("utf-8 path"),
+ "--model",
+ "stub-model",
+ "--provider",
+ "stub",
+ "--output-format",
+ "stream-json",
+ "--input-format",
+ "stream-json",
+ "say hi",
+ ])
+ .stdin(Stdio::null())
+ .output()
+ .expect("run the jan CLI")
+ }
+
+ fn command(&self, args: &[&str]) -> Command {
+ std::fs::create_dir_all(self.home()).expect("home dir");
+ std::fs::create_dir_all(self.project()).expect("project dir");
+ let mut cmd = Command::new(env!("CARGO_BIN_EXE_jan"));
+ cmd.args(args)
+ .env("HOME", self.home())
+ .env("JAN_DATA_FOLDER", self.root.join("jan-data"))
+ .env_remove("JAN_API_KEY")
+ .env_remove("OPENAI_API_KEY")
+ .env_remove("ANTHROPIC_API_KEY");
+ cmd
+ }
+}
+
+impl Drop for Scratch {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.root);
+ }
+}
+
+/// Parse stdout as the NDJSON stream it promises: one object per line, and a
+/// non-empty first one.
+fn records(out: &Output) -> Vec<serde_json::Value> {
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ let lines: Vec<&str> = stdout.lines().filter(|l| !l.trim().is_empty()).collect();
+ assert!(
+ !lines.is_empty(),
+ "no stream at all.\nstdout:\n{stdout}\nstderr:\n{}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ lines
+ .iter()
+ .map(|line| {
+ serde_json::from_str(line)
+ .unwrap_or_else(|e| panic!("not one JSON object per line: {e}\n{line}"))
+ })
+ .collect()
+}
+
+/// The handshake itself, field by field, and the ordering that makes it a
+/// handshake: it is the first thing on the channel and it appears once.
+fn assert_handshake(first: &serde_json::Value, project: &Path) {
+ assert_eq!(
+ first["type"], "init",
+ "the first record is not the handshake"
+ );
+ assert_eq!(first["protocol_version"], 1);
+ let session_id = first["session_id"].as_str().expect("a session id");
+ assert!(!session_id.is_empty(), "the handshake names no session");
+ assert_eq!(first["model"], "stub-model");
+ assert_eq!(
+ first["cwd"].as_str().expect("a cwd"),
+ std::fs::canonicalize(project)
+ .expect("canonical project")
+ .to_string_lossy(),
+ );
+ let tools = first["tools"].as_array().expect("a tool list");
+ assert!(
+ tools.iter().any(|t| t == "read"),
+ "the handshake advertises no read tool: {tools:?}"
+ );
+ assert_eq!(
+ first["input_kinds"],
+ serde_json::json!(["user", "abort", "permission"]),
+ "a client is told what it may send back"
+ );
+}
+
+#[test]
+fn a_successful_run_opens_with_the_handshake() {
+ let scratch = Scratch::new("ok");
+ let url = stub_provider("200 OK", "text/event-stream", ANSWER);
+ scratch.configure(&url);
+
+ let out = scratch.run();
+ let records = records(&out);
+
+ assert_handshake(&records[0], &scratch.project());
+ assert_eq!(
+ records.iter().filter(|r| r["type"] == "init").count(),
+ 1,
+ "the handshake is emitted once"
+ );
+
+ let last = records.last().expect("a terminal record");
+ assert_eq!(last["type"], "result", "the envelope terminates the stream");
+ assert_eq!(
+ last["is_error"], false,
+ "the stub answered, so this run passes: {last}"
+ );
+ assert_eq!(last["result"], "stub answer");
+
+ // The two ids are one session: the handshake carries it whole, the
+ // envelope the short form `--resume` also accepts.
+ let announced = records[0]["session_id"].as_str().expect("a session id");
+ assert_eq!(
+ last["session_id"].as_str().expect("a saved session"),
+ &announced[..8],
+ "the envelope must name the session the handshake announced"
+ );
+}
+
+#[test]
+fn a_failing_run_still_opens_with_the_handshake() {
+ let scratch = Scratch::new("fail");
+ let url = stub_provider("400 Bad Request", "application/json", REFUSAL);
+ scratch.configure(&url);
+
+ let out = scratch.run();
+ let records = records(&out);
+
+ assert_handshake(&records[0], &scratch.project());
+ let last = records.last().expect("a terminal record");
+ assert_eq!(last["type"], "result");
+ assert_eq!(
+ last["is_error"], true,
+ "a refused request must fail the run: {last}"
+ );
+ assert_eq!(
+ last["session_id"],
+ serde_json::Value::Null,
+ "nothing was saved, so the envelope names no session -- which is how a \
+ client knows the id from `init` is not on disk"
+ );
+}
+
+/// A run that fails before a model is resolved has no session and no tool set
+/// to name, so it reports the failure and nothing else. Documented rather than
+/// incidental: it is the one stream a client will not see a handshake on, and
+/// `error.code` says which kind of failure it is.
+#[test]
+fn a_setup_failure_reports_the_envelope_without_a_handshake() {
+ let scratch = Scratch::new("setup");
+ let project = scratch.project();
+ let out = scratch
+ .command(&[
+ "cli",
+ "agent",
+ "run",
+ "--project",
+ project.to_str().expect("utf-8 path"),
+ "--output-format",
+ "stream-json",
+ "say hi",
+ ])
+ .stdin(Stdio::null())
+ .output()
+ .expect("run the jan CLI");
+
+ let records = records(&out);
+ assert_eq!(
+ records.len(),
+ 1,
+ "a setup failure reports once: {records:?}"
+ );
+ assert_eq!(records[0]["type"], "result");
+ assert_eq!(records[0]["is_error"], true);
+ assert_eq!(records[0]["error"]["code"], "setup_error");
+ assert_eq!(records[0]["session_id"], serde_json::Value::Null);
+}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
index 306f5bdf0..1595c2901 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
@@ -115,7 +115,7 @@ pub struct MonitorUpdate {
}
/// Display-only view of one active monitor, for a status panel.
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MonitorSnapshot {
pub monitor_id: String,
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index 7cdfd187e..c67cb8281 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -4,7 +4,23 @@
//! (the upstream call streams via SSE) plus per-step progress and one terminal
//! `Done`/`Error`.
-#[derive(Clone, Debug, serde::Serialize)]
+/// Version of the wire contract the event stream speaks, carried as
+/// `protocol_version` on the headless channel's `init` record and in the
+/// terminal envelope of `--output-format json`.
+///
+/// Bump it only for a change a v1 consumer cannot survive: a renamed or removed
+/// tag, a removed field, or a new meaning for an existing one. Adding a variant
+/// or a field is not a bump -- the contract requires a consumer to ignore what
+/// it does not know, which is what lets a provider-neutral field land without
+/// breaking anyone. The full rule is documented next to the channel it governs,
+/// in `docs/src/pages/docs/agent/cli.mdx` under `jan cli agent run`.
+pub const PROTOCOL_VERSION: u32 = 1;
+
+/// `Deserialize` as well as `Serialize`: a consumer validates what it received
+/// against these shapes (and, for a future `jan cli agent schema`, generates its
+/// own types from them), so the wire has to survive a round trip, not just a
+/// write. `#[serde(tag = "type")]` keeps the tag on both sides.
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StreamEvent {
/// A streamed content delta from the model.
@@ -207,7 +223,7 @@ pub enum StreamEvent {
/// across the plan, and its blackboard file) and 1-based phase number. Carried by
/// [`StreamEvent::SubagentPlan`] so a consumer can show it waiting on the phase
/// before it.
-#[derive(Clone, Debug, serde::Serialize)]
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct PendingSubagent {
pub name: String,
pub phase: u32,
@@ -283,7 +299,7 @@ fn arg_name(args: &serde_json::Value) -> String {
.unwrap_or_default()
}
-#[derive(Clone, Debug, Default, serde::Serialize)]
+#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct Usage {
pub prompt_tokens: Option<u64>,
pub completion_tokens: Option<u64>,
@@ -326,11 +342,291 @@ impl Usage {
}
}
+/// Test-only, and reachable from the sibling test in `core::cli::run_report`
+/// that checks the documented tag list against these variants: the table has to
+/// live with the enum it enumerates, but the contract it defends is the one the
+/// CLI channel documents.
#[cfg(test)]
-mod tests {
+pub(crate) mod tests {
use super::*;
use serde_json::json;
+ /// One instance of every variant, paired with the variant's name as the
+ /// enum spells it. The tag is read from serde when this list is serialized,
+ /// so a variant's tag is never restated here -- only its coverage is.
+ ///
+ /// [`every_variant_is_sampled`] is what keeps this list honest: it matches
+ /// every variant with no wildcard arm, so adding one to `StreamEvent` fails
+ /// the build until it is added here too.
+ pub(crate) fn sample_events() -> Vec<(&'static str, StreamEvent)> {
+ vec![
+ ("Token", StreamEvent::Token { text: "hi".into() }),
+ ("Reasoning", StreamEvent::Reasoning { text: "hmm".into() }),
+ ("Step", StreamEvent::Step { index: 1, max: 0 }),
+ (
+ "ToolCallStarted",
+ StreamEvent::ToolCallStarted {
+ id: "t1".into(),
+ name: "read".into(),
+ },
+ ),
+ (
+ "ToolCallArgsDelta",
+ StreamEvent::ToolCallArgsDelta {
+ id: "t1".into(),
+ delta: "{\"pa".into(),
+ },
+ ),
+ (
+ "ToolCall",
+ StreamEvent::ToolCall {
+ id: "t1".into(),
+ name: "read".into(),
+ args: json!({ "path": "a.txt" }),
+ },
+ ),
+ (
+ "ToolOutputDelta",
+ StreamEvent::ToolOutputDelta {
+ id: "t1".into(),
+ delta: "line\n".into(),
+ },
+ ),
+ (
+ "ToolResult",
+ StreamEvent::ToolResult {
+ id: "t1".into(),
+ content: "ok".into(),
+ is_error: false,
+ diff: Some("-a\n+b\n".into()),
+ },
+ ),
+ (
+ "SubagentStart",
+ StreamEvent::SubagentStart {
+ run_id: "r1".into(),
+ name: "scout".into(),
+ task: Some("look".into()),
+ },
+ ),
+ (
+ "SubagentQueued",
+ StreamEvent::SubagentQueued {
+ run_id: "r1".into(),
+ name: "scout".into(),
+ task: None,
+ waiting: 2,
+ },
+ ),
+ (
+ "SubagentEnd",
+ StreamEvent::SubagentEnd {
+ run_id: "r1".into(),
+ name: "scout".into(),
+ error: Some("boom".into()),
+ },
+ ),
+ (
+ "SubagentPlan",
+ StreamEvent::SubagentPlan {
+ pending: vec![PendingSubagent {
+ name: "scout".into(),
+ phase: 2,
+ }],
+ },
+ ),
+ (
+ "Subagent",
+ StreamEvent::Subagent {
+ run_id: "r1".into(),
+ name: "scout".into(),
+ event: Box::new(StreamEvent::Token { text: "hi".into() }),
+ },
+ ),
+ (
+ "Notice",
+ StreamEvent::Notice {
+ text: "monitor matched".into(),
+ },
+ ),
+ (
+ "Monitors",
+ StreamEvent::Monitors {
+ monitors: vec![tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot {
+ monitor_id: "m1".into(),
+ name: "ci".into(),
+ script: "true".into(),
+ polls: 3,
+ }],
+ },
+ ),
+ ("Parked", StreamEvent::Parked),
+ (
+ "MessagesUpdated",
+ StreamEvent::MessagesUpdated {
+ messages: vec![json!({ "role": "user", "content": "hi" })],
+ },
+ ),
+ (
+ "AskRequest",
+ StreamEvent::AskRequest {
+ request_id: "ask-1".into(),
+ request: crate::core::agent::interaction::AskRequest {
+ questions: vec![crate::core::agent::interaction::Question {
+ id: "q1".into(),
+ question: "which?".into(),
+ options: vec![crate::core::agent::interaction::OptionItem {
+ label: "a".into(),
+ description: None,
+ }],
+ multi: false,
+ recommended: Some(0),
+ }],
+ },
+ timeout_secs: Some(30),
+ },
+ ),
+ (
+ "AskResolved",
+ StreamEvent::AskResolved {
+ request_id: "ask-1".into(),
+ },
+ ),
+ (
+ "TodoUpdate",
+ StreamEvent::TodoUpdate {
+ list: crate::core::agent::todo::TodoList {
+ phases: vec![crate::core::agent::todo::TodoPhase {
+ name: "Implement".into(),
+ tasks: vec![crate::core::agent::todo::TodoItem {
+ content: "wire the record".into(),
+ status: crate::core::agent::todo::TodoStatus::InProgress,
+ }],
+ }],
+ },
+ },
+ ),
+ (
+ "TurnUsage",
+ StreamEvent::TurnUsage {
+ usage: Usage {
+ prompt_tokens: Some(120),
+ completion_tokens: Some(8),
+ total_tokens: Some(128),
+ cached_tokens: Some(64),
+ cache_write_tokens: None,
+ },
+ },
+ ),
+ (
+ "Done",
+ StreamEvent::Done {
+ stop_reason: "stop".into(),
+ usage: None,
+ },
+ ),
+ (
+ "Error",
+ StreamEvent::Error {
+ code: "upstream_error".into(),
+ message: "boom".into(),
+ },
+ ),
+ (
+ "PermissionRequest",
+ StreamEvent::PermissionRequest {
+ request_id: "perm-1".into(),
+ tool_name: "bash".into(),
+ capability: "exec".into(),
+ path: None,
+ command: Some("ls".into()),
+ diff: None,
+ prompt_kind: "exec".into(),
+ offers_always: true,
+ },
+ ),
+ ]
+ }
+
+ /// Exhaustive on purpose: a variant added to `StreamEvent` stops this
+ /// matching, and the error names the arm that is missing, which is the
+ /// prompt to add it to [`sample_events`] as well.
+ #[allow(dead_code)]
+ fn every_variant_is_sampled(ev: &StreamEvent) {
+ match ev {
+ StreamEvent::Token { .. }
+ | StreamEvent::Reasoning { .. }
+ | StreamEvent::Step { .. }
+ | StreamEvent::ToolCallStarted { .. }
+ | StreamEvent::ToolCallArgsDelta { .. }
+ | StreamEvent::ToolCall { .. }
+ | StreamEvent::ToolOutputDelta { .. }
+ | StreamEvent::ToolResult { .. }
+ | StreamEvent::SubagentStart { .. }
+ | StreamEvent::SubagentQueued { .. }
+ | StreamEvent::SubagentEnd { .. }
+ | StreamEvent::SubagentPlan { .. }
+ | StreamEvent::Subagent { .. }
+ | StreamEvent::Notice { .. }
+ | StreamEvent::Monitors { .. }
+ | StreamEvent::Parked
+ | StreamEvent::MessagesUpdated { .. }
+ | StreamEvent::AskRequest { .. }
+ | StreamEvent::AskResolved { .. }
+ | StreamEvent::TodoUpdate { .. }
+ | StreamEvent::TurnUsage { .. }
+ | StreamEvent::Done { .. }
+ | StreamEvent::Error { .. }
+ | StreamEvent::PermissionRequest { .. } => {}
+ }
+ }
+
+ /// A consumer validates what it receives against these shapes, so every
+ /// variant has to survive a write/read pair unchanged -- optional fields
+ /// included, since a `skip_serializing_if` field that cannot be read back is
+ /// how a consumer ends up with a struct it cannot deserialize at all.
+ #[test]
+ fn every_variant_round_trips_through_the_wire() {
+ let samples = sample_events();
+ assert!(samples.len() >= 24, "{} variants sampled", samples.len());
+ for (name, ev) in samples {
+ let line = serde_json::to_string(&ev).expect(name);
+ let back: StreamEvent = serde_json::from_str(&line)
+ .unwrap_or_else(|e| panic!("{name} does not read back: {e}\n{line}"));
+ assert_eq!(
+ serde_json::to_value(&back).unwrap(),
+ serde_json::to_value(&ev).unwrap(),
+ "{name} changed across a round trip"
+ );
+ }
+ }
+
+ /// `sample_events` pairs each instance with its variant name, and this is
+ /// what makes the pairing meaningful: the names it uses are the ones the
+ /// enum declares, and no two variants share a tag.
+ #[test]
+ fn sampled_names_are_distinct_and_match_their_tags() {
+ let mut names: Vec<&str> = sample_events().iter().map(|(name, _)| *name).collect();
+ let total = names.len();
+ names.sort_unstable();
+ names.dedup();
+ assert_eq!(names.len(), total, "a variant is sampled twice");
+
+ let mut tags: Vec<String> = sample_events()
+ .iter()
+ .map(|(name, ev)| {
+ serde_json::to_value(ev).unwrap()["type"]
+ .as_str()
+ .unwrap_or_else(|| panic!("{name} has no tag"))
+ .to_string()
+ })
+ .collect();
+ let total = tags.len();
+ tags.sort();
+ tags.dedup();
+ assert_eq!(tags.len(), total, "two variants share one tag");
+ }
+
#[test]
fn token_serializes_with_snake_case_tag() {
let v = serde_json::to_value(StreamEvent::Token { text: "hi".into() }).unwrap();
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index cd3a2a160..9f109cf62 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -735,9 +735,11 @@ use crate::core::agent::r#loop::{
};
use tauri_plugin_agent_tools::workspace;
use crate::core::cli::providers::{load_provider_configs, ProviderOverrides};
-use crate::core::cli::run_report::{ndjson_line, OutputFormat, PermissionDecisionRecord, RunReport};
+use crate::core::cli::run_report::{
+ ndjson_line, Init, OutputFormat, PermissionDecisionRecord, RunReport,
+};
use crate::core::cli::stream_input::{
- parse_input_line, InputErrorRecord, InputFormat, InputMessage, StreamInput,
+ parse_input_line, InputErrorRecord, InputFormat, InputMessage, StreamInput, INPUT_KINDS,
};
use crate::core::mcp::models::McpSettings;
use std::collections::HashMap;
@@ -1821,6 +1823,66 @@ async fn run_agent_loop(
}
}
+ // The session this run saves under, decided here rather than at save time
+ // so the `init` record can name it: a client learns the id it can `--resume`
+ // from the first line of the stream, and a run killed mid-flight still told
+ // it which id to look for.
+ let session_id = persist
+ .thread_id
+ .clone()
+ .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
+
+ // The handshake, before anything else can reach stdout. Printed here rather
+ // than from the printer task for exactly that reason: nothing has been
+ // spawned yet, so "first line" is a property of the code's order rather than
+ // a race against the run's own events.
+ //
+ // The tool names come from the same resolution the first turn uses, so the
+ // handshake cannot advertise a set the request does not carry.
+ if format.is_stream_json() {
+ let tools = crate::core::agent::r#loop::context_advertised_tools(
+ &args.mcp_servers,
+ &args.mcp_settings,
+ &args.permissions,
+ args.project_root.as_deref(),
+ args.run_mode,
+ args.subagents_enabled,
+ args.max_parallel_subagents,
+ args.ask_requests.is_some(),
+ args.todo_registry.is_some(),
+ )
+ .await
+ .iter()
+ .filter_map(|tool| {
+ tool.get("function")?
+ .get("name")?
+ .as_str()
+ .map(str::to_string)
+ })
+ .collect();
+ let cwd = match args.project_root.as_deref() {
+ Some(root) => root.to_string_lossy().into_owned(),
+ None => std::env::current_dir()
+ .map(|d| d.to_string_lossy().into_owned())
+ .unwrap_or_default(),
+ };
+ // A run that does not read stdin accepts nothing, and says so: an empty
+ // list is a client's answer that there is no reply path, which is more
+ // use than an absent field or a list of kinds the run will ignore.
+ let input_kinds = if input_format.is_stream_json() {
+ INPUT_KINDS.to_vec()
+ } else {
+ Vec::new()
+ };
+ print_json_line(&Init::new(
+ &session_id,
+ &persist.model,
+ &cwd,
+ tools,
+ input_kinds,
+ ));
+ }
+
// 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
@@ -1896,7 +1958,11 @@ async fn run_agent_loop(
if let Some(messages) = updated_history {
history = messages;
}
- let mut session_id = thread_id.clone();
+ // What the envelope reports. A resumed thread already exists on disk, so it
+ // is named even when the run fails; a fresh one is only named once it has
+ // actually been saved -- which is also how a client tells whether the
+ // `init` id names a session it can read back.
+ let mut reported_session_id = thread_id.clone();
let mut final_text = None;
if let Ok(completion) = result.as_ref() {
final_text = completion_text(completion);
@@ -1904,7 +1970,7 @@ async fn run_agent_loop(
history.push(serde_json::json!({ "role": "assistant", "content": text.clone() }));
}
let metadata = worktree_metadata(&agent_dir, thread_id.as_deref(), workspace.as_ref());
- match cli_save_thread(&agent_dir, thread_id.as_deref(), &model, &history, metadata) {
+ match cli_save_thread(&agent_dir, Some(&session_id), &model, &history, metadata) {
Ok(id) => {
if !format.is_machine() {
eprintln!(
@@ -1913,7 +1979,7 @@ async fn run_agent_loop(
short_id(&id)
);
}
- session_id = Some(id);
+ reported_session_id = Some(id);
}
Err(e) => eprintln!("(could not save session: {e})"),
}
@@ -1922,7 +1988,7 @@ async fn run_agent_loop(
print_report(
format,
report.finish(
- session_id.as_deref().map(short_id).as_deref(),
+ reported_session_id.as_deref().map(short_id).as_deref(),
provider.as_deref(),
&model,
started.elapsed().as_millis(),
diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rs
index 761136112..646130cb8 100644
--- a/src-tauri/src/core/cli/run_report.rs
+++ b/src-tauri/src/core/cli/run_report.rs
@@ -15,9 +15,15 @@
//! `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`.
+//! `turn_usage`, `done`, `error`, `permission_request`. Three tags are minted
+//! here rather than by the loop: `init`, `permission_decision` and `result`.
+//! `init` is the handshake a client reads before any other record (see
+//! [`Init`]); `permission_decision` reports how this CLI answered a gated tool
+//! call, which the loop never sees; `result` is the terminal envelope.
+//!
+//! The tag lists above and in `events.rs` are the contract, and a test compares
+//! both against the variants that actually serialize -- a renamed tag is a
+//! breaking change for every consumer, so it must not be able to land quietly.
//!
//! `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
@@ -165,6 +171,7 @@ StreamEvent::TurnUsage { usage } => {
let is_error = self.error.is_some();
RunResult {
kind: "result",
+ protocol_version: crate::core::agent::events::PROTOCOL_VERSION,
is_error,
result: super::tui::answer_without_reasoning(final_text.unwrap_or(&self.partial)),
stop_reason: if is_error {
@@ -197,6 +204,80 @@ StreamEvent::TurnUsage { usage } => {
}
}
+/// The first record of a `--output-format stream-json` channel, and the only
+/// one a client may require before any other.
+///
+/// It exists because the rest of the stream is unversioned and unaddressable: a
+/// consumer sees events and nothing else, so it cannot tell which contract it
+/// is reading, whose run it is watching, or what it is allowed to send back.
+/// Those are the questions a handshake answers, and a consumer that has to
+/// infer them from a side channel (a CLI flag it passed, a config file it read)
+/// is one refactor away from being wrong.
+///
+/// Field names are snake_case like the rest of this channel -- the event tags
+/// and the envelope's `session_id`/`stop_reason` set that convention, so the
+/// handshake follows it rather than introducing a second one for two fields.
+///
+/// The compatibility rule for what a client may assume:
+///
+/// - a v1 client may rely on `protocol_version`, `session_id` and `model`
+/// always being present;
+/// - fields may be added without a version bump, so a client ignores unknown
+/// ones and unknown tags rather than failing;
+/// - a tag is never renamed and never removed within v1;
+/// - behaviour beyond v1 is asserted against `protocol_version`, not assumed.
+#[derive(serde::Serialize)]
+pub(crate) struct Init {
+ #[serde(rename = "type")]
+ kind: &'static str,
+ /// [`PROTOCOL_VERSION`](crate::core::agent::events::PROTOCOL_VERSION) at
+ /// the time of the run, so a client can refuse a channel it cannot read
+ /// instead of misreading it.
+ protocol_version: u32,
+ /// The thread this run saves under. Minted before the first turn rather
+ /// than at save time, so a client learns the id from the stream: the same
+ /// id `--resume` takes. A run that produces no completion saves nothing,
+ /// and its terminal envelope reports `session_id: null` -- which is how a
+ /// client tells this id apart from one that now exists on disk.
+ ///
+ /// The envelope reports the short form (the first 8 characters) it has
+ /// always reported; this is the same id, unabbreviated.
+ session_id: String,
+ /// The model this run dispatches to, as the envelope reports it.
+ model: String,
+ /// The project root the run's tools are confined to, absolute.
+ cwd: String,
+ /// The tool names this run advertises, in the order the request carries
+ /// them. Order matters to the consumer: it is the prefix of the request a
+ /// provider caches on, so a set that reorders between runs is a cache miss
+ /// (see the tool-ordering note in `upstream.rs`).
+ tools: Vec<String>,
+ /// What `--input-format stream-json` accepts from this client, as message
+ /// `type` tags. Empty when the run does not read stdin at all, which is
+ /// the honest answer for a read-only stream: nothing can be sent back.
+ input_kinds: Vec<&'static str>,
+}
+
+impl Init {
+ pub(crate) fn new(
+ session_id: &str,
+ model: &str,
+ cwd: &str,
+ tools: Vec<String>,
+ input_kinds: Vec<&'static str>,
+ ) -> Self {
+ Self {
+ kind: "init",
+ protocol_version: crate::core::agent::events::PROTOCOL_VERSION,
+ session_id: session_id.to_string(),
+ model: model.to_string(),
+ cwd: cwd.to_string(),
+ tools,
+ input_kinds,
+ }
+ }
+}
+
/// The envelope itself. A struct rather than a `json!` literal so the fields
/// serialize in declaration order: `serde_json`'s map is sorted, which would
/// print this contract alphabetically and bury `result` in the middle.
@@ -204,6 +285,10 @@ StreamEvent::TurnUsage { usage } => {
pub(crate) struct RunResult {
#[serde(rename = "type")]
kind: &'static str,
+ /// The same contract version `init` carries, so a `--output-format json`
+ /// caller -- which never sees an init record -- can still pin what it is
+ /// reading. Additive: a consumer that does not know the field ignores it.
+ protocol_version: u32,
is_error: bool,
result: String,
stop_reason: String,
@@ -267,6 +352,167 @@ mod tests {
use super::*;
use crate::core::agent::events::Usage;
+ /// The backticked tags in the module doc comment, read from the sentence
+ /// that introduces them. Deliberately a parse of the prose: a list nothing
+ /// reads is how the tags and the enum drifted apart in the first place, and
+ /// the failure mode of a rewording is a test that says so, not a consumer
+ /// that meets an unknown tag in production.
+ fn documented_tags_after<'a>(source: &'a str, marker: &str) -> Vec<&'a str> {
+ let start = source
+ .find(marker)
+ .unwrap_or_else(|| panic!("the doc comment no longer says {marker:?}"))
+ + marker.len();
+ let mut tags = Vec::new();
+ let mut cursor = start;
+ // A period between two backticked words ends the list: that is the
+ // sentence boundary, and everything past it is other prose.
+ while let Some(open) = source[cursor..].find('`').map(|i| cursor + i) {
+ if source[cursor..open].contains('.') {
+ break;
+ }
+ let Some(close) = source[open + 1..].find('`').map(|i| open + 1 + i) else {
+ break;
+ };
+ tags.push(&source[open + 1..close]);
+ cursor = close + 1;
+ }
+ tags
+ }
+
+ /// The variant names the enum declares, read from its own source. The enum
+ /// body's variants sit at one indentation level, which is what makes them
+ /// distinguishable from the fields inside them.
+ fn declared_variants(source: &str) -> Vec<&str> {
+ let body = source
+ .split_once("pub enum StreamEvent {")
+ .expect("the enum's declaration moved")
+ .1;
+ body.split("\n}")
+ .next()
+ .expect("the enum is unterminated")
+ .lines()
+ .filter_map(|line| {
+ let name = line.strip_prefix(" ")?;
+ if name.starts_with(' ') || name.starts_with("//") || name.starts_with("#[") {
+ return None;
+ }
+ let end = name
+ .find(|c: char| !c.is_alphanumeric())
+ .unwrap_or(name.len());
+ let name = &name[..end];
+ (!name.is_empty() && name.starts_with(char::is_uppercase)).then_some(name)
+ })
+ .collect()
+ }
+
+ /// Three views of one contract: the tags the doc comment promises, the
+ /// variants the enum declares, and the tags its instances actually
+ /// serialize. A renamed tag breaks consumers, so it has to be a deliberate
+ /// edit in all three places rather than a silent one in the enum.
+ #[test]
+ fn the_documented_tags_are_the_variants_that_serialize() {
+ let source = include_str!("run_report.rs");
+ let loop_tags = documented_tags_after(source, "the snake_case variant names: ");
+ let minted =
+ documented_tags_after(source, "tags are minted here rather than by the loop: ");
+
+ let samples = crate::core::agent::events::tests::sample_events();
+ let mut serialized: Vec<String> = samples
+ .iter()
+ .map(|(name, ev)| {
+ serde_json::to_value(ev).unwrap()["type"]
+ .as_str()
+ .unwrap_or_else(|| panic!("{name} has no tag"))
+ .to_string()
+ })
+ .collect();
+ serialized.sort();
+
+ let mut documented: Vec<String> = loop_tags
+ .iter()
+ .chain(minted.iter())
+ .map(|t| t.to_string())
+ .collect();
+ documented.sort();
+
+ assert_eq!(
+ documented, serialized,
+ "the tags this module documents and the tags that serialize have diverged"
+ );
+ }
+
+ /// The tag list must cover every variant the enum declares, not just the
+ /// ones sampled: a variant nobody samples is a tag a consumer can meet
+ /// while the documentation still denies it exists.
+ #[test]
+ fn every_declared_variant_is_documented_and_sampled() {
+ let enum_source = include_str!("../agent/events.rs");
+ let mut declared = declared_variants(enum_source);
+ declared.sort_unstable();
+ assert!(declared.len() >= 24, "{} variants", declared.len());
+
+ let mut sampled: Vec<&str> = crate::core::agent::events::tests::sample_events()
+ .iter()
+ .map(|(name, _)| *name)
+ .collect();
+ sampled.sort_unstable();
+ assert_eq!(
+ sampled, declared,
+ "the sample list and the enum's own variants disagree"
+ );
+ }
+
+ /// The handshake's wire shape, field by field. A consumer asserting
+ /// `protocol_version == 1` at startup is the whole point of the record, so
+ /// the name and the version it carries are the contract, not an internal
+ /// detail that a rename may move.
+ #[test]
+ fn init_carries_the_version_and_the_run_it_names() {
+ let out = serde_json::to_value(Init::new(
+ "3f7a91c2-0000-0000-0000-000000000000",
+ "stub-model",
+ "/tmp/project",
+ vec!["read".to_string(), "write".to_string()],
+ vec!["user", "abort", "permission"],
+ ))
+ .unwrap();
+ assert_eq!(
+ out,
+ serde_json::json!({
+ "type": "init",
+ "protocol_version": crate::core::agent::events::PROTOCOL_VERSION,
+ "session_id": "3f7a91c2-0000-0000-0000-000000000000",
+ "model": "stub-model",
+ "cwd": "/tmp/project",
+ "tools": ["read", "write"],
+ "input_kinds": ["user", "abort", "permission"],
+ })
+ );
+ }
+
+ /// A run that does not read stdin accepts nothing, and the record says so
+ /// with an empty list rather than by omitting the field: a client asking
+ /// "may I send anything back?" gets an answer either way.
+ #[test]
+ fn init_with_no_input_channel_advertises_no_kinds() {
+ let out =
+ serde_json::to_value(Init::new("id", "m", "/tmp", Vec::new(), Vec::new())).unwrap();
+ assert_eq!(out["input_kinds"], serde_json::json!([]));
+ assert_eq!(out["input_kinds"].as_array().unwrap().len(), 0);
+ }
+
+ /// The envelope carries the same version, so a `--output-format json`
+ /// caller -- which never sees an `init` record -- can pin it too.
+ #[test]
+ fn the_envelope_carries_the_protocol_version() {
+ let out = RunReport::default().finish(None, None, "m", 1, None);
+ let out = serde_json::to_value(out).unwrap();
+ assert_eq!(
+ out["protocol_version"],
+ serde_json::json!(crate::core::agent::events::PROTOCOL_VERSION)
+ );
+ }
+
fn usage(prompt: u64, completion: u64) -> Usage {
Usage {
prompt_tokens: Some(prompt),
diff --git a/src-tauri/src/core/cli/stream_input.rs b/src-tauri/src/core/cli/stream_input.rs
index b0c83135b..a0fcd0600 100644
--- a/src-tauri/src/core/cli/stream_input.rs
+++ b/src-tauri/src/core/cli/stream_input.rs
@@ -12,6 +12,8 @@
//! `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).
+//! [`INPUT_KINDS`] is that set as data: the `init` record advertises it, so a
+//! client learns what it may send without being told out of band.
//! 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.
@@ -38,6 +40,13 @@ impl InputFormat {
}
}
+/// The message kinds the input channel accepts, in the order they are
+/// documented. One list, two readers: the rejection message below names them,
+/// and the `init` record advertises them to a client that has not read the
+/// docs. A kind added to the parser without a line here would be a capability
+/// no client is told about, so a test pins the two together.
+pub(crate) const INPUT_KINDS: [&str; 3] = ["user", "abort", "permission"];
+
/// One well-formed line from the client.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum InputMessage {
@@ -96,7 +105,10 @@ pub(crate) fn parse_input_line(line: &str) -> Result<InputMessage, String> {
decision,
})
}
- other => Err(format!("unknown type '{other}' (user, abort, permission)")),
+ other => Err(format!(
+ "unknown type '{other}' ({})",
+ INPUT_KINDS.join(", ")
+ )),
}
}
@@ -205,6 +217,31 @@ mod tests {
);
}
+ /// The advertised kinds and the accepted ones are one list. A kind the
+ /// parser takes but the handshake never names is a capability no client can
+ /// discover; one it names but cannot parse is a lie a client acts on. The
+ /// `panic!` arm is the prompt to add a sample line when the list grows.
+ #[test]
+ fn the_advertised_kinds_are_the_accepted_ones() {
+ let err = parse_input_line(r#"{"type":"steer","text":"hi"}"#).expect_err("unknown type");
+ for kind in INPUT_KINDS {
+ assert!(
+ err.contains(kind),
+ "the rejection does not name '{kind}': {err}"
+ );
+ let line = match kind {
+ "user" => r#"{"type":"user","text":"hello"}"#,
+ "abort" => r#"{"type":"abort"}"#,
+ "permission" => r#"{"type":"permission","request_id":"p1","decision":"deny"}"#,
+ other => panic!("'{other}' is advertised but has no sample line here"),
+ };
+ assert!(
+ parse_input_line(line).is_ok(),
+ "'{kind}' is advertised in init but the parser rejects it"
+ );
+ }
+ }
+
/// Every rejection names what was wrong: the client sees this text on the
/// stream and has nothing else to debug against.
#[test]