Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cli): serve agent sessions over JSON-RPC on stdin/stdout
thinhlpg443cf722f249
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 1a7925f4b..e65696c65 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -509,6 +509,11 @@ enum AgentCommands {#[arg(long)]out: Option<std::path::PathBuf>,},+ /// Serve addressable sessions over JSON-RPC on stdin/stdout+ Rpc,+ /// Print the RPC request and event schemas, generated from the types that+ /// define the envelope+ RpcSchema,}/// Read/write the user-wide `~/.jan/config.toml` provider store. This is the@@ -729,7 +734,18 @@ async fn main() {// no separate ping to fire here; `JAN_CLI_NO_UPDATE_CHECK` opts out of both.// `jan mcp serve` is driven by another program, not a person: nobody reads// the notice, and an update fetch on every spawn is a cost the peer pays.- if !matches!(command, Commands::Update { .. } | Commands::Mcp { .. }) {+ // `jan cli agent rpc` is the same deal - the peer owns the process, and a+ // notice on stdout would land inside the protocol channel.+ if !matches!(+ command,+ Commands::Update { .. }+ | Commands::Mcp { .. }+ | Commands::Cli {+ cmd: CliCommands::Agent {+ cmd: AgentCommands::Rpc+ }+ }+ ) {app_lib::core::cli::updater::print_update_notice_if_available().await;}@@ -1017,6 +1033,13 @@ async fn handle_agent(cmd: AgentCommands) {// No project and no provider: the schema comes from the types alone, so// it is the same document on any machine and in any directory.AgentCommands::Schema { out } => app_lib::core::cli::protocol_schema::run(out.as_deref()),+ AgentCommands::Rpc => app_lib::core::cli::rpc::serve().await,+ // Like `schema`: no project root and no provider are involved, so the+ // document is the same one on any machine.+ AgentCommands::RpcSchema => {+ println!("{}", app_lib::core::cli::rpc_schema::document());+ Ok(())+ }};if let Err(e) = result {eprintln!("Error: {e}");@@ -1588,6 +1611,31 @@ mod tests {assert_eq!(out.as_deref(), Some(std::path::Path::new("protocol/schema.json")));}+ /// `rpc` and `rpc-schema` are the long-lived session transport and its+ /// generated schema: neither involves a project, a provider, or a flag.+ #[test]+ fn rpc_subcommands_parse() {+ let cli = Cli::parse_from(["jan", "cli", "agent", "rpc"]);+ assert!(matches!(+ cli.command,+ Some(Commands::Cli {+ cmd: CliCommands::Agent {+ cmd: AgentCommands::Rpc+ }+ })+ ));++ let cli = Cli::parse_from(["jan", "cli", "agent", "rpc-schema"]);+ assert!(matches!(+ cli.command,+ Some(Commands::Cli {+ cmd: CliCommands::Agent {+ cmd: AgentCommands::RpcSchema+ }+ })+ ));+ }+#[test]fn update_command_parses() {let cli = Cli::parse_from(["jan", "update"]);diff --git a/src-tauri/jan-cli/tests/agent_rpc.rs b/src-tauri/jan-cli/tests/agent_rpc.rsnew file mode 100644index 000000000..74eec314b--- /dev/null+++ b/src-tauri/jan-cli/tests/agent_rpc.rs@@ -0,0 +1,305 @@+//! Exercise the persistent RPC process through the real `jan` binary.+use std::io::{BufRead, BufReader, Write};+use std::net::TcpListener;+use std::path::{Path, PathBuf};+use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};+use std::time::Duration;++/// A stub OpenAI-compatible provider that streams `tokens` deltas and then stops.+fn provider(tokens: usize) -> String {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!("http://{}/v1", listener.local_addr().unwrap());+ std::thread::spawn(move || {+ for connection in listener.incoming() {+ let Ok(mut stream) = connection else { break };+ stream+ .set_read_timeout(Some(Duration::from_secs(10)))+ .unwrap();+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut headers = String::new();+ loop {+ let mut line = String::new();+ reader.read_line(&mut line).unwrap();+ if line == "\r\n" || line.is_empty() {+ break;+ }+ headers.push_str(&line);+ }+ let size = headers+ .lines()+ .find_map(|line| {+ line.to_ascii_lowercase()+ .strip_prefix("content-length:")+ .and_then(|n| n.trim().parse::<usize>().ok())+ })+ .unwrap_or(0);+ let mut request = vec![0; size];+ std::io::Read::read_exact(&mut reader, &mut request).unwrap();+ let mut answer = String::new();+ for index in 0..tokens.max(1) {+ let text = if index == 0 {+ "stub answer"+ } else {+ " and more"+ };+ let chunk = serde_json::json!({+ "id":"stub-1","object":"chat.completion.chunk","created":1,"model":"stub-model",+ "choices":[{"index":0,"delta":{"role":"assistant","content":text},"finish_reason":null}]+ });+ answer.push_str(&format!("data: {chunk}\n\n"));+ }+ answer.push_str("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");+ answer.push_str("data: [DONE]\n\n");+ write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", answer.len()).unwrap();+ }+ });+ url+}++/// A scratch directory of our own, so the two tests never share a `~/.jan`.+fn scratch(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("jan-rpc-{name}-{}", std::process::id()));+ std::fs::create_dir_all(dir.join("home")).unwrap();+ std::fs::create_dir_all(dir.join("project")).unwrap();+ dir+}++/// Point the CLI at the stub provider, so a session can resolve a model.+fn configure(home: &Path, base_url: &str) {+ let configured = Command::new(env!("CARGO_BIN_EXE_jan"))+ .args([+ "config",+ "set",+ "--provider",+ "stub",+ "--api-key",+ "test-key",+ "--base-url",+ base_url,+ "--model",+ "stub-model",+ ])+ .env("HOME", home)+ .env("JAN_CLI_NO_UPDATE_CHECK", "1")+ .output()+ .unwrap();+ assert!(+ configured.status.success(),+ "{}",+ String::from_utf8_lossy(&configured.stderr)+ );+}++/// The RPC process as a client drives it: LF-delimited frames in and out.+struct Rpc {+ child: Child,+ input: ChildStdin,+ output: BufReader<ChildStdout>,+}++impl Rpc {+ fn open(home: &Path) -> Self {+ let mut child = Command::new(env!("CARGO_BIN_EXE_jan"))+ .args(["cli", "agent", "rpc"])+ .env("JAN_CLI_NO_UPDATE_CHECK", "1")+ .env("HOME", home)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .spawn()+ .expect("launch rpc process");+ let input = child.stdin.take().unwrap();+ let output = BufReader::new(child.stdout.take().unwrap());+ Self {+ child,+ input,+ output,+ }+ }++ fn read(&mut self) -> serde_json::Value {+ let mut line = String::new();+ assert!(+ self.output.read_line(&mut line).unwrap() > 0,+ "the channel closed with no record"+ );+ serde_json::from_str(&line).expect("one JSON-RPC line")+ }++ fn send(&mut self, frame: serde_json::Value) {+ writeln!(self.input, "{frame}").unwrap();+ self.input.flush().unwrap();+ }++ /// One request, and the one frame it is answered with.+ fn ask(&mut self, request: serde_json::Value) -> serde_json::Value {+ self.send(request);+ self.read()+ }++ /// `initialize` and then `initialized`: the guard every method sits behind.+ fn handshake(&mut self) {+ let init = self.ask(serde_json::json!({"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":1,"clientInfo":{"name":"test","version":"1"},"capabilities":{}}}));+ assert_eq!(init["result"]["protocolVersion"], 1);+ self.send(serde_json::json!({"jsonrpc":"2.0","method":"initialized","params":{}}));+ }++ fn start_session(&mut self, cwd: &Path) -> String {+ let started = self.ask(serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/start","params":{"cwd":cwd,"model":"stub-model"}}));+ let session_id = started["result"]["sessionId"].as_str().unwrap_or_default();+ assert!(!session_id.is_empty(), "{started}");+ session_id.to_owned()+ }++ /// Close stdin and wait: the process ends when the client says so.+ fn close(mut self) {+ drop(self.input);+ assert!(self.child.wait().unwrap().success());+ }+}++#[test]+fn rpc_serves_a_session_lifecycle_after_the_handshake() {+ let scratch = scratch("lifecycle");+ let home = scratch.join("home");+ let provider_url = provider(1);+ configure(&home, &provider_url);+ let mut rpc = Rpc::open(&home);++ let refused =+ rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":1,"method":"session/list","params":{}}));+ assert_eq!(refused["error"]["code"], -32002);+ rpc.handshake();++ let project = scratch.join("project");+ let session_id = rpc.start_session(&project);+ let incompatible = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":11,"method":"session/start","params":{"cwd":project,"model":"stub-model","tools":[{"name":"host_tool"}]}}));+ assert_eq!(incompatible["error"]["code"], -32602);+ let invalid_image = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":12,"method":"turn/start","params":{"sessionId":session_id,"input":[{"type":"image_url","image_url":{"url":"data:image/bmp;base64,AA=="}}]}}));+ assert_eq!(invalid_image["error"]["code"], -32602);+ let unknown =+ rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":13,"method":"not-a-method","params":{}}));+ assert_eq!(unknown["error"]["code"], -32601);+ // Malformed JSON is a transport fault with its own code, and it does not+ // desynchronize the channel: the next request is still answered.+ writeln!(rpc.input, "{{not json").unwrap();+ rpc.input.flush().unwrap();+ let parse_error = rpc.read();+ assert_eq!(parse_error["error"]["code"], -32700, "{parse_error}");+ // An unknown additive notification is ignored rather than fatal: a frame+ // with no id gets no answer, so the next frame the client reads is the+ // response to the request it sent after it.+ rpc.send(serde_json::json!({"jsonrpc":"2.0","method":"not-a-notification","params":{}}));+ let after = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":15,"method":"session/list","params":{}}));+ assert_eq!(after["id"], 15, "{after}");++ let turn = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":4,"method":"turn/start","params":{"sessionId":session_id,"input":"say hi"}}));+ assert!(turn["result"]["turnId"].as_str().is_some(), "{turn}");+ let mut terminal = None;+ let mut saw_text = false;+ for _ in 0..40 {+ let record = rpc.read();+ if record["method"] == "item/token" {+ assert_eq!(record["params"]["event"]["text"], "stub answer");+ saw_text = true;+ }+ if record["method"] == "turn/completed" {+ terminal = Some(record);+ break;+ }+ }+ let terminal = terminal.expect("a terminal outcome after the streamed events");+ assert_eq!(terminal["params"]["turnId"], turn["result"]["turnId"]);+ assert_eq!(terminal["params"]["stopReason"], "completed");+ assert!(saw_text, "the real provider's streamed token reaches RPC");+ assert!(+ project+ .join(".jan/agent/threads")+ .join(&session_id)+ .exists(),+ "completed non-ephemeral turn persists under its RPC session id"+ );++ let listed =+ rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":5,"method":"session/list","params":{}}));+ assert_eq!(listed["result"]["sessions"][0]["turns"], 1, "{listed}");+ let resumed = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":6,"method":"session/resume","params":{"sessionId":session_id}}));+ assert_eq!(resumed["result"]["sessionId"], session_id, "{resumed}");++ let pending = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":9,"method":"turn/start","params":{"sessionId":session_id,"input":"continue"}}));+ assert!(pending["result"]["turnId"].is_string(), "{pending}");+ let busy = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":14,"method":"turn/start","params":{"sessionId":session_id,"input":"overlapping turn"}}));+ assert_eq!(busy["error"]["code"], -32001, "{busy}");+ assert_eq!(busy["error"]["data"]["retryable"], true);+ rpc.send(serde_json::json!({"jsonrpc":"2.0","id":10,"method":"turn/interrupt","params":{"sessionId":session_id}}));+ let mut interrupted = 0;+ let mut acknowledged = false;+ for _ in 0..40 {+ let record = rpc.read();+ if record["method"] == "turn/completed"+ && record["params"]["turnId"] == pending["result"]["turnId"]+ {+ assert_eq!(record["params"]["stopReason"], "interrupted");+ interrupted += 1;+ }+ if record["id"] == 10 {+ assert_eq!(record["result"], serde_json::json!({}));+ acknowledged = true;+ }+ if interrupted == 1 && acknowledged {+ break;+ }+ }+ assert!(acknowledged && interrupted == 1);++ let archived = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":7,"method":"session/archive","params":{"sessionId":session_id}}));+ assert_eq!(archived["result"], serde_json::json!({}), "{archived}");+ let gone = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":8,"method":"session/resume","params":{"sessionId":session_id}}));+ assert_eq!(gone["error"]["code"], -32602);++ rpc.close();+ let _ = std::fs::remove_dir_all(scratch);+}++/// A client that stops reading cannot grow the server without bound: the queue+/// fills at its cap, the run ends with a terminal outcome that says so, and+/// that outcome still reaches the client once it reads again.+#[test]+fn rpc_ends_the_turn_a_client_stopped_reading() {+ let scratch = scratch("overload");+ let home = scratch.join("home");+ let provider_url = provider(8_000);+ configure(&home, &provider_url);+ let mut rpc = Rpc::open(&home);+ rpc.handshake();++ let project = scratch.join("project");+ let session_id = rpc.start_session(&project);+ let turn = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":4,"method":"turn/start","params":{"sessionId":session_id,"input":"talk"}}));+ assert!(turn["result"]["turnId"].is_string(), "{turn}");++ // Stop reading. The writer blocks on the pipe, the bounded queue fills+ // behind it, and the producer ends the turn instead of buffering the+ // 8000 deltas the provider still has to send.+ std::thread::sleep(Duration::from_secs(2));++ let mut terminal = None;+ for _ in 0..10_000 {+ let record = rpc.read();+ if record["method"] == "turn/completed" {+ terminal = Some(record);+ break;+ }+ }+ let terminal = terminal.expect("a terminal outcome after the queue overloaded");+ assert_eq!(terminal["params"]["turnId"], turn["result"]["turnId"]);+ assert_eq!(terminal["params"]["stopReason"], "error", "{terminal}");+ assert!(+ terminal["params"]["error"]+ .as_str()+ .is_some_and(|error| error.contains("overloaded")),+ "{terminal}"+ );++ rpc.close();+ let _ = std::fs::remove_dir_all(scratch);+}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 98955b4f6..982934cda 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -17,6 +17,10 @@ pub mod model_catalog;mod path_refs;/// `jan cli agent schema`: the protocol's JSON Schema, generated from the types.pub mod protocol_schema;+/// `jan cli agent rpc`: persistent, session-scoped JSON-RPC transport.+pub mod rpc;+/// `jan cli agent rpc-schema`: the RPC request and event schemas.+pub mod rpc_schema;pub mod run_report;pub mod providers;mod secret_input;diff --git a/src-tauri/src/core/cli/rpc.rs b/src-tauri/src/core/cli/rpc.rsnew file mode 100644index 000000000..0d9d33a1a--- /dev/null+++ b/src-tauri/src/core/cli/rpc.rs@@ -0,0 +1,405 @@+//! Session-scoped JSON-RPC over LF-delimited stdio. Stdout contains only protocol records.+use std::collections::HashMap;+use std::io::{BufRead, Write};+use std::sync::Arc;++use serde_json::{json, Value};+use tokio::sync::{mpsc, Mutex};+use tokio::task::JoinHandle;++use super::providers::ProviderOverrides;+use super::rpc_schema::{InitializeParams, SessionStartParams};+use super::stream_input::{parse_input_line, MAX_LINE_BYTES};+use super::{agent_dir_for, cli_save_thread, prepare_agent_session, AgentSession, SessionFlags};+use crate::core::agent::events::{StreamEvent, PROTOCOL_VERSION};+use crate::core::agent::r#loop::{run_orchestration_steered, SteeringRequest};++const OUTPUT_CAPACITY: usize = 1025; // 1024 ordinary records and one reserved terminal outcome.+const INPUT_CAPACITY: usize = 64;++struct Session {+ agent: AgentSession,+ history: Vec<Value>,+ id: String,+ turns: u32,+ ephemeral: bool,+}++struct ActiveTurn {+ session_id: String,+ turn_id: String,+ events: mpsc::Receiver<TurnMessage>,+ runner: JoinHandle<()>,+ steerer: JoinHandle<()>,+ pending: Arc<Mutex<Vec<Value>>>,+ updated_history: Option<Vec<Value>>,+}++enum TurnMessage {+ Event(StreamEvent),+ Finished(Result<Value, String>),+}++fn response(id: &Value, result: Value) -> Value {+ json!({"jsonrpc":"2.0","id":id,"result":result})+}++fn error(id: &Value, code: i32, message: &str) -> Value {+ let data = (code == -32001).then(|| json!({"retryable":true}));+ json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message,"data":data}})+}++fn send(out: &mpsc::Sender<Value>, record: Value) -> Result<(), String> {+ out.try_send(record)+ .map_err(|_| "RPC output queue is full or closed".to_owned())+}++fn notify(out: &mpsc::Sender<Value>, method: &str, params: Value) -> Result<(), String> {+ send(+ out,+ json!({"jsonrpc":"2.0","method":method,"params":params}),+ )+}++fn read_line(reader: &mut impl BufRead) -> std::io::Result<Option<(Vec<u8>, bool)>> {+ let mut line = Vec::new();+ let mut too_long = false;+ loop {+ let available = reader.fill_buf()?;+ if available.is_empty() {+ return Ok((!line.is_empty()).then_some((line, too_long)));+ }+ let n = available+ .iter()+ .position(|byte| *byte == b'\n')+ .map_or(available.len(), |index| index + 1);+ if !too_long {+ let available_bytes = MAX_LINE_BYTES.saturating_sub(line.len());+ line.extend_from_slice(&available[..n.min(available_bytes)]);+ too_long = n > available_bytes;+ }+ let done = available[n - 1] == b'\n';+ reader.consume(n);+ if done {+ return Ok(Some((line, too_long)));+ }+ }+}++fn input_lines() -> mpsc::Receiver<(Vec<u8>, bool)> {+ let (tx, rx) = mpsc::channel(INPUT_CAPACITY);+ std::thread::spawn(move || {+ let mut stdin = std::io::stdin().lock();+ while let Ok(Some(line)) = read_line(&mut stdin) {+ if tx.blocking_send(line).is_err() {+ break;+ }+ }+ });+ rx+}++fn output_lines(mut rx: mpsc::Receiver<Value>) -> std::thread::JoinHandle<()> {+ std::thread::spawn(move || {+ let stdout = std::io::stdout();+ let mut writer = stdout.lock();+ while let Some(value) = rx.blocking_recv() {+ if serde_json::to_writer(&mut writer, &value).is_err()+ || writer.write_all(b"\n").is_err()+ || writer.flush().is_err()+ {+ break;+ }+ }+ })+}++fn start_turn(session: &mut Session, input: Value) -> ActiveTurn {+ session.history.push(json!({"role":"user","content":input}));+ let body = session.agent.body(json!(session.history));+ let args = session.agent.args.clone();+ let (events, receiver) = mpsc::channel(64);+ let (steering_tx, mut steering_rx) = mpsc::unbounded_channel::<SteeringRequest>();+ let pending = Arc::new(Mutex::new(Vec::<Value>::new()));+ let queued = Arc::clone(&pending);+ let steerer = tokio::spawn(async move {+ while let Some(request) = steering_rx.recv().await {+ let messages = std::mem::take(&mut *queued.lock().await);+ let _ = request.reply.send(messages);+ }+ });+ let runner = tokio::spawn(async move {+ let (tx, mut rx) = mpsc::unbounded_channel();+ let forward = tokio::spawn({+ let events = events.clone();+ async move {+ while let Some(event) = rx.recv().await {+ if events.send(TurnMessage::Event(event)).await.is_err() {+ break;+ }+ }+ }+ });+ let result = run_orchestration_steered(&tx, &body, &args, Some(&steering_tx)).await;+ drop(tx);+ let _ = forward.await;+ let _ = events.send(TurnMessage::Finished(result)).await;+ });+ ActiveTurn {+ session_id: session.id.clone(),+ turn_id: uuid::Uuid::new_v4().to_string(),+ events: receiver,+ runner,+ steerer,+ pending,+ updated_history: None,+ }+}++fn finish_turn(+ sessions: &mut HashMap<String, Session>,+ turn: ActiveTurn,+ out: &mpsc::Sender<Value>,+ result: Result<Value, String>,+ interrupted: bool,+) -> Result<(), String> {+ turn.steerer.abort();+ let session = sessions+ .get_mut(&turn.session_id)+ .ok_or("active session missing")?;+ if let Some(history) = turn.updated_history {+ session.history = history;+ }+ let stop_reason = if interrupted {+ "interrupted"+ } else if result.is_ok() {+ "completed"+ } else {+ "error"+ };+ let mut error_message = if interrupted {+ None+ } else {+ result.as_ref().err().cloned()+ };+ if let Ok(completion) = &result {+ if let Some(text) = super::completion_text(completion) {+ session+ .history+ .push(json!({"role":"assistant","content":text}));+ }+ if !session.ephemeral {+ if let Some(project) = session.agent.args.project_root.as_ref() {+ if let Err(message) = cli_save_thread(+ &agent_dir_for(project),+ Some(&session.id),+ &session.agent.model,+ &session.history,+ None,+ ) {+ error_message = Some(format!("could not save session: {message}"));+ }+ }+ }+ }+ session.turns += 1;+ notify(+ out,+ "turn/completed",+ json!({+ "sessionId":turn.session_id,"turnId":turn.turn_id,+ "stopReason":if error_message.is_some() { "error" } else { stop_reason },"error":error_message+ }),+ )+}++/// One runtime owns many addressable sessions. All writes share one bounded output queue.+pub async fn serve() -> Result<(), String> {+ let mut input = input_lines();+ let (out, writer) = mpsc::channel(OUTPUT_CAPACITY);+ let writer = output_lines(writer);+ let mut initialized = false;+ let mut negotiated = false;+ let mut sessions = HashMap::<String, Session>::new();+ let mut active: Option<ActiveTurn> = None;+ loop {+ tokio::select! {+ message = input.recv() => {+ let Some((line, too_long)) = message else { break; };+ if too_long {+ send(&out, error(&Value::Null, -32600, "Input line exceeds max_line_bytes"))?;+ continue;+ }+ let request: Value = match serde_json::from_slice(&line) {+ Ok(value) => value,+ Err(_) => { send(&out, error(&Value::Null, -32700, "Parse error"))?; continue; }+ };+ let id = request.get("id").cloned().unwrap_or(Value::Null);+ let method = request.get("method").and_then(Value::as_str).unwrap_or("");+ let params = &request["params"];+ if request["jsonrpc"] != "2.0" || method.is_empty() {+ send(&out, error(&id, -32600, "Invalid Request"))?;+ continue;+ }+ if method == "initialize" {+ let reply = match serde_json::from_value::<InitializeParams>(params.clone()) {+ Ok(init) if init.protocol_version == PROTOCOL_VERSION && !init.client_info.name.is_empty() && !init.client_info.version.is_empty() => {+ negotiated = true;+ response(&id, json!({"protocolVersion":PROTOCOL_VERSION,"serverInfo":{"name":"jan","version":env!("CARGO_PKG_VERSION")},"capabilities":{"session":true,"turn":true}}))+ }+ _ => error(&id, -32602, "Unsupported protocol version or malformed clientInfo"),+ };+ send(&out, reply)?;+ continue;+ }+ if method == "initialized" && negotiated && id.is_null() {+ initialized = true;+ continue;+ }+ if !initialized {+ send(&out, error(&id, -32002, "Server not initialized"))?;+ continue;+ }+ let reply = match method {+ "session/start" => {+ match serde_json::from_value::<SessionStartParams>(params.clone()) {+ Err(_) => error(&id, -32602, "session/start requires cwd and supported options"),+ Ok(start) if !std::path::Path::new(&start.cwd).is_dir() => error(&id, -32602, "cwd is not a directory"),+ Ok(start) => match prepare_agent_session(&start.cwd, start.model, ProviderOverrides::default(), SessionFlags { require_model: true, ..Default::default() }, None) {+ Ok(agent) => {+ let sid = uuid::Uuid::new_v4().to_string();+ sessions.insert(sid.clone(), Session { agent, history: Vec::new(), id: sid.clone(), turns: 0, ephemeral: start.ephemeral });+ response(&id, json!({"sessionId":sid}))+ }+ Err(message) => error(&id, -32602, &message),+ },+ }+ }+ "session/list" => response(&id, json!({"sessions":sessions.values().map(|s| json!({"id":s.id,"model":s.agent.model,"turns":s.turns})).collect::<Vec<_>>()})),+ "session/resume" => match params["sessionId"].as_str() {+ Some(sid) => match sessions.get(sid) {+ Some(session) => response(&id, json!({"sessionId":sid,"model":session.agent.model,"turns":session.turns})),+ None => error(&id, -32602, "unknown sessionId (RPC sessions belong to their process)"),+ },+ None => error(&id, -32602, "session/resume requires sessionId"),+ },+ "session/fork" => match params["sessionId"].as_str() {+ Some(sid) if active.as_ref().is_some_and(|t| t.session_id == sid) => error(&id, -32001, "session busy"),+ Some(sid) if sessions.contains_key(sid) => {+ let source = sessions.get(sid).expect("checked");+ let project = source.agent.args.project_root.as_deref().ok_or("session has no project root")?;+ let agent = prepare_agent_session(&project.to_string_lossy(), Some(source.agent.model.clone()), ProviderOverrides::default(), SessionFlags { require_model: true, ..Default::default() }, None)?;+ let fork = uuid::Uuid::new_v4().to_string();+ let history = source.history.clone();+ let ephemeral = source.ephemeral;+ sessions.insert(fork.clone(), Session { agent, history, id: fork.clone(), turns: 0, ephemeral });+ response(&id, json!({"sessionId":fork}))+ }+ _ => error(&id, -32602, "unknown sessionId"),+ },+ "session/archive" => match params["sessionId"].as_str() {+ Some(sid) if active.as_ref().is_some_and(|t| t.session_id == sid) => error(&id, -32001, "session busy"),+ Some(sid) if sessions.remove(sid).is_some() => response(&id, json!({})),+ _ => error(&id, -32602, "unknown sessionId"),+ },+ "turn/start" => {+ if active.is_some() {+ error(&id, -32001, "another turn is active; retry after turn/completed")+ } else if let (Some(sid), Some(input)) = (params["sessionId"].as_str(), params.get("input")) {+ let parsed = json!({"type":"user","content":input});+ let content = if let Some(text) = input.as_str() {+ parse_input_line(&json!({"type":"user","text":text}).to_string()).map(|_| Value::String(text.to_owned()))+ } else if input.is_array() {+ parse_input_line(&parsed.to_string()).map(|_| input.clone())+ } else { Err("input must be text or content parts".to_string()) };+ match (sessions.get_mut(sid), content) {+ (Some(session), Ok(content)) => {+ let turn = start_turn(session, content);+ let tid = turn.turn_id.clone();+ active = Some(turn);+ response(&id, json!({"turnId":tid}))+ }+ (None, _) => error(&id, -32602, "unknown sessionId"),+ (_, Err(message)) => error(&id, -32602, &message),+ }+ } else { error(&id, -32602, "turn/start requires sessionId and input") }+ }+ "turn/steer" => match (active.as_ref(), params["sessionId"].as_str(), params["input"].as_str()) {+ (Some(turn), Some(sid), Some(text)) if turn.session_id == sid && !text.trim().is_empty() => {+ turn.pending.lock().await.push(json!({"role":"user","content":text}));+ response(&id, json!({}))+ }+ _ => error(&id, -32602, "turn/steer requires an active session and nonempty input"),+ },+ "turn/interrupt" => match (active.take(), params["sessionId"].as_str()) {+ (Some(turn), Some(sid)) if turn.session_id == sid => {+ turn.runner.abort();+ if let Some(session) = sessions.get_mut(sid) {+ session.agent.permission_requests.lock().await.clear();+ }+ finish_turn(&mut sessions, turn, &out, Err("interrupted".to_owned()), true)?;+ response(&id, json!({}))+ }+ (other, _) => {+ active = other;+ error(&id, -32602, "no active turn for sessionId")+ }+ },+ "permission/respond" => match (active.as_ref(), params["requestId"].as_str(), params["decision"].as_str()) {+ (Some(turn), Some(request_id), Some(decision)) => {+ let decision = match decision {+ "allow_once" => Some(tauri_plugin_agent_tools::tools::gate::PermissionDecision::AllowOnce),+ "allow_always" => Some(tauri_plugin_agent_tools::tools::gate::PermissionDecision::AllowAlways),+ "deny" => Some(tauri_plugin_agent_tools::tools::gate::PermissionDecision::Deny),+ _ => None,+ };+ if let Some(decision) = decision {+ let session = sessions.get(&turn.session_id).expect("active session");+ match session.agent.permission_requests.lock().await.remove(request_id) {+ Some(sender) => { let _ = sender.send(decision); response(&id, json!({})) }+ None => error(&id, -32602, "no permission request is pending"),+ }+ } else { error(&id, -32602, "invalid permission decision") }+ }+ _ => error(&id, -32602, "permission/respond requires an active turn and requestId"),+ },+ _ => error(&id, -32601, "Method not found"),+ };+ if !id.is_null() { out.send(reply).await.map_err(|_| "RPC client closed stdout".to_string())?; }+ }+ message = async { active.as_mut().expect("active").events.recv().await }, if active.is_some() => {+ let Some(message) = message else { continue; };+ let turn = active.as_mut().expect("active");+ match message {+ TurnMessage::Event(event) => {+ if let StreamEvent::MessagesUpdated { messages } = &event { turn.updated_history = Some(messages.clone()); }+ let wire = serde_json::to_value(&event).map_err(|e| e.to_string())?;+ let method = format!("item/{}", wire["type"].as_str().ok_or("event has no tag")?);+ // Leave the terminal slot free. On overflow, terminate the run+ // rather than accumulating unbounded model deltas.+ if out.capacity() <= 1 {+ let turn = active.take().expect("active");+ turn.runner.abort();+ finish_turn(&mut sessions, turn, &out, Err("RPC output queue overloaded".to_owned()), false)?;+ } else {+ notify(&out, &method, json!({"sessionId":turn.session_id,"turnId":turn.turn_id,"event":wire}))?;+ }+ }+ TurnMessage::Finished(result) => {+ let turn = active.take().expect("active");+ finish_turn(&mut sessions, turn, &out, result, false)?;+ }+ }+ }+ }+ }+ if let Some(turn) = active {+ turn.runner.abort();+ turn.steerer.abort();+ }+ drop(out);+ writer+ .join()+ .map_err(|_| "RPC output writer panicked".to_string())?;+ Ok(())+}diff --git a/src-tauri/src/core/cli/rpc_schema.rs b/src-tauri/src/core/cli/rpc_schema.rsnew file mode 100644index 000000000..c12a8f477--- /dev/null+++ b/src-tauri/src/core/cli/rpc_schema.rs@@ -0,0 +1,93 @@+//! The typed request shapes accepted by the JSON-RPC dispatcher. Schemas are+//! derived from the same types that deserialize incoming params.+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct InitializeParams {+ pub protocol_version: u32,+ pub client_info: ClientInfo,+ #[serde(default)]+ pub capabilities: serde_json::Value,+}++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(deny_unknown_fields)]+pub struct ClientInfo {+ pub name: String,+ pub version: String,+}++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct SessionStartParams {+ pub cwd: String,+ pub model: Option<String>,+ #[serde(default)]+ pub ephemeral: bool,+}++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct SessionIdParams {+ pub session_id: String,+}++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct TurnStartParams {+ pub session_id: String,+ pub input: serde_json::Value,+}++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct TurnSteerParams {+ pub session_id: String,+ pub input: String,+}++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct PermissionResponseParams {+ pub request_id: String,+ pub decision: String,+}++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct RpcEnvelope {+ pub jsonrpc: String,+ pub id: Option<serde_json::Value>,+ pub method: String,+ pub params: Option<serde_json::Value>,+}++#[derive(Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct RpcNotification {+ pub jsonrpc: &'static str,+ pub method: String,+ pub params: serde_json::Value,+}++pub fn document() -> serde_json::Value {+ serde_json::json!({+ "protocol_version": crate::core::agent::events::PROTOCOL_VERSION,+ "envelope": schemars::schema_for!(RpcEnvelope),+ "requests": {+ "initialize": schemars::schema_for!(InitializeParams),+ "session/start": schemars::schema_for!(SessionStartParams),+ "session/resume": schemars::schema_for!(SessionIdParams),+ "session/fork": schemars::schema_for!(SessionIdParams),+ "session/archive": schemars::schema_for!(SessionIdParams),+ "turn/start": schemars::schema_for!(TurnStartParams),+ "turn/steer": schemars::schema_for!(TurnSteerParams),+ "turn/interrupt": schemars::schema_for!(SessionIdParams),+ "permission/respond": schemars::schema_for!(PermissionResponseParams)+ },+ "notifications": schemars::schema_for!(RpcNotification),+ "events": schemars::schema_for!(crate::core::agent::events::StreamEvent)+ })+}