Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cli): host tool contract -- declare tools the client executes, dispatch calls to it (#9048)
Akarshan Biswas7f25519b2d81
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdxindex 1de322e4d..e09a3c897 100644--- a/docs/src/pages/docs/agent/cli.mdx+++ b/docs/src/pages/docs/agent/cli.mdx@@ -110,6 +110,7 @@ jan cli agent run --max-turns 5 --max-session-tokens 20000 "triage the build fai| `--provider`, `--api-key` | Credential overrides for this run || `--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` |+| `--host-tools <FILE>` | JSON file declaring tools **the client executes**, as a list of `{"name", "description", "parameters"}`. The model calls them as `host__<name>`; each call arrives as a `tool_request` on stdout and must be answered with a `tool_result` on stdin, so this requires `--input-format stream-json`. Validated before the run starts |<Callout type="info">`run` takes a positional task, so a space-separated `--resume ID` would swallow it. Write the value@@ -194,8 +195,8 @@ knowingly unfinished. A CI job that must distinguish them should read `stop_reas#### 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.+text, tool calls, tool results, permission requests, and tool 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 stdinfor the run's lifetime. It requires `--output-format stream-json`, because the client is the only@@ -206,6 +207,7 @@ thing that can answer a permission request and it needs to be reading them.| Follow-up turn | `{"type":"user","text":"also check the tests"}` || Follow-up turn with an image | `{"type":"user","content":[{"type":"text","text":"what changed here?"},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgo..."}}]}` || Permission answer | `{"type":"permission","request_id":"perm-1","decision":"allow_once"}` |+| Host tool result | `{"type":"tool_result","request_id":"host-1","content":"{\"ok\":true}","is_error":false}` || Stop the run | `{"type":"abort"}` |A follow-up joins the run at the next turn boundary. A `user` message carries either `text` or@@ -223,6 +225,33 @@ it crossed.line that parses as none of these is reported as an `input_error` record and skipped, so one badline cannot end a healthy run.+#### Host tools++A host tool is one the **client** implements: a device only the host can reach, an editor's own+buffer, anything whose state does not live in this process. Declare the set with `--host-tools`,+and the run advertises each to the model as `host__<name>`.++When the model calls one, the run emits a `tool_request` and waits:++```json+{"type":"tool_request","request_id":"host-1","tool_name":"robot_arm_move","args":{"position":"bin"}}+```++`tool_name` is the name **you declared**, not the `host__`-prefixed one the model calls: you+dispatch on the name you chose. Answer it with a `tool_result` carrying the same `request_id`.+`content` is a string and is required even for a failure -- set `is_error: true` and put the reason+in `content`, which reaches the model as the tool's error. Each `request_id` is answerable once.++A host tool is gated exactly as an MCP tool is: prompted rather than auto-approved (its+`permission_request` carries `prompt_kind: "mcp"`, the class for any opaque third-party+capability, naming the qualified `host__<name>`), withheld entirely in read-only plan mode, and+subject to the same deny list. The `init` handshake echoes the schemas actually advertised in+`tool_specs`, so a tool you declared but that is missing there was withheld by policy and will+never be called.++Because only the client can answer, a `tool_request` left unanswered when stdin closes is failed+rather than left to hang: the model is told the client is gone and the turn finishes.+<Callout type="info">Closing stdin is not an abort -- the run finishes and still prints its `result`. But it does end theonly thing that can approve a gated tool call, so any request still pending is denied, as is any@@ -235,7 +264,7 @@ The first line of a `stream-json` run is always an `init` record, printed beforeevent:```json-{"type":"init","protocol_version":1,"session_id":"3f7a91c2-4e5d-4a6b-8c7d-0e1f2a3b4c5d","model":"tokamak-1-preview","cwd":"/home/me/app","tools":["read","write","bash"],"input_kinds":["user","abort","permission"],"input_content_parts":{"mime_types":["image/png","image/jpeg","image/gif","image/webp"],"max_image_bytes":5242880,"max_message_image_bytes":10485760,"max_images":8,"max_line_bytes":16777216,"max_echo_bytes":4096}}+{"type":"init","protocol_version":1,"session_id":"3f7a91c2-4e5d-4a6b-8c7d-0e1f2a3b4c5d","model":"tokamak-1-preview","cwd":"/home/me/app","tools":["read","write","bash","host__robot_arm_move"],"tool_specs":[{"type":"function","function":{"name":"host__robot_arm_move","description":"Move the arm.","parameters":{"type":"object"}}}],"input_kinds":["user","abort","permission","tool_result"],"input_content_parts":{"mime_types":["image/png","image/jpeg","image/gif","image/webp"],"max_image_bytes":5242880,"max_message_image_bytes":10485760,"max_images":8,"max_line_bytes":16777216,"max_echo_bytes":4096}}```| Field | Notes |@@ -245,6 +274,7 @@ event:| `model` | The model the run dispatches to, as `result` reports it || `cwd` | The project root the run's tools are confined to. `null` when the run was given none || `tools` | The tool names the request advertises, in the order it sends them. The tool array is the head of the cached request prefix, so the order is part of the payload, not a detail |+| `tool_specs` | The full schemas of the host tools this run advertises, so a host can check its constraints survived rather than trusting that they did. The advertised subset, not everything declared: a tool withheld by the deny list or plan mode is absent. Omitted entirely when the run advertises no host tools || `input_kinds` | The `type` values this run accepts on stdin. Empty when the run was not asked to read stdin, so "nothing can be sent back" is an answer rather than a missing field || `input_content_parts` | The content-part form of `user` and the caps a client must stay inside: `mime_types`, `max_image_bytes`, `max_message_image_bytes`, `max_images`, plus the channel-wide `max_line_bytes` and `max_echo_bytes`. `null` when the run reads no stdin. Additive, so a client that reads only `input_kinds` is unaffected |@@ -303,7 +333,7 @@ The document has two root properties:| Property | Contents || --- | --- || `output` | The records a run writes to stdout: every `StreamEvent`, plus the `init`, `result`, `permission_decision` and `input_error` records the CLI adds around the loop |-| `input` | The lines a client may write to stdin: the `user`, `abort` and `permission` messages |+| `input` | The lines a client may write to stdin: the `user`, `abort`, `permission` and `tool_result` messages |`x-protocol-version` is the contract version the document describes, so a client validates againstthe version it pinned rather than whatever happens to be installed. `$defs` names the record types,diff --git a/protocol/schema.json b/protocol/schema.jsonindex 4036f5433..77ee953b7 100644--- a/protocol/schema.json+++ b/protocol/schema.json@@ -327,7 +327,7 @@]},{- "description": "A backgrounded subagent's own internal event, tagged with its run so a\nconsumer can attribute it to the right child even when several run\nconcurrently. `event` is a non-terminal child event (Token/Step/ToolCall/\nToolResult/PermissionRequest); the child's terminal Done/Error is never\nwrapped (its result is delivered via `await_subagent`).",+ "description": "A backgrounded subagent's own internal event, tagged with its run so a\nconsumer can attribute it to the right child even when several run\nconcurrently. `event` is a non-terminal child event (Token/Step/ToolCall/\nToolResult/PermissionRequest); the child's terminal Done/Error is never\nwrapped (its result is delivered via `await_subagent`).\n\nNever a `ToolRequest`: a client answers a request by `request_id` on\nstdin, and it is told nothing about this wrapper, so a nested request\nwould be unanswerable. `run_subagent` clears the child's host tool set\nrather than relying on this, which is why the case cannot arise.","type": "object","properties": {"run_id": {@@ -606,6 +606,31 @@"prompt_kind","offers_always"]+ },+ {+ "description": "A host-registered tool was called and the run is waiting for the host to\nexecute it. The client replies with a `tool_result` line carrying this\n`request_id`; until it does, the turn is parked on this one call.\n\n`tool_name` is the name the *host* declared, not the `host__`-prefixed\nname the model calls: the host dispatches on the name it chose and never\nhas to know this layer's prefixing rule.",+ "type": "object",+ "properties": {+ "request_id": {+ "type": "string"+ },+ "tool_name": {+ "type": "string"+ },+ "args": {+ "description": "The arguments the model produced, already parsed from the call's\nJSON string. Validated against nothing here -- the host owns the\nschema it declared and is the only party that can enforce it."+ },+ "type": {+ "type": "string",+ "const": "tool_request"+ }+ },+ "required": [+ "type",+ "request_id",+ "tool_name",+ "args"+ ]}]},@@ -860,6 +885,11 @@"type": "string"}},+ "tool_specs": {+ "description": "The full schemas of the host tools this run advertises. A host compares\nthese against what it declared, which is the only way to know its\nconstraints survived rather than trusting that they did; the names in\n`tools` alone cannot answer that.\n\nThis is the advertised subset, not everything declared: a deny list, an\nallowlist or Plan mode can withhold a host tool, and its absence here is\nhow a host learns that happened. Omitted entirely when the run\nadvertises no host tools, so an ordinary run's handshake is unchanged.",+ "type": "array",+ "items": true+ },"input_kinds": {"description": "What `--input-format stream-json` accepts from this client, as message\n`type` tags. Empty when the run does not read stdin at all, which is\nthe honest answer for a read-only stream: nothing can be sent back.","type": "array",@@ -1134,7 +1164,7 @@]},"InputLine": {- "description": "One input line, as the wire shape: the three [`INPUT_KINDS`], with the fields\neach carries. The wire shape is a serde type rather than a hand-rolled walk\nover a `Value` so the protocol schema can be derived from it -- `jan cli\nagent schema` publishes this shape, and a hand-written copy of it would be\ncorrect only until the parser moved.\n\nThe `type` field is read separately, before deserializing: an unknown kind is\nreported against [`INPUT_KINDS`], which is the list `init` advertises.",+ "description": "One input line, as the wire shape: the [`INPUT_KINDS`], with the fields\neach carries. The wire shape is a serde type rather than a hand-rolled walk\nover a `Value` so the protocol schema can be derived from it -- `jan cli\nagent schema` publishes this shape, and a hand-written copy of it would be\ncorrect only until the parser moved.\n\nThe `type` field is read separately, before deserializing: an unknown kind is\nreported against [`INPUT_KINDS`], which is the list `init` advertises.","oneOf": [{"description": "A follow-up turn for the run in flight: `text`, or `content` as an\nOpenAI content-part array. Exactly one of the two, which JSON Schema\ncannot state, so the doc says it and the parser enforces it. A\ncontent-part message carries text parts and `image_url` parts, whose URL\nis a base64 `data:` URL -- the run shares no filesystem with a client.",@@ -1195,6 +1225,31 @@"request_id","decision"]+ },+ {+ "description": "The answer to a `tool_request` this run emitted: the host executed the\ntool and this is its result, which becomes the model's tool message.\n\n`content` is required even for a failure. A tool message with nothing in\nit tells the model only that something happened, which is worse than a\nshort error.",+ "type": "object",+ "properties": {+ "request_id": {+ "type": "string"+ },+ "content": {+ "type": "string"+ },+ "is_error": {+ "type": "boolean",+ "default": false+ },+ "type": {+ "type": "string",+ "const": "tool_result"+ }+ },+ "required": [+ "type",+ "request_id",+ "content"+ ]}]},diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 1a7925f4b..849bab081 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -469,12 +469,19 @@ enum AgentCommands {/// 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+ /// `stream-json` reads newline-delimited `user`, `permission`,+ /// `abort` and `tool_result` 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,+ /// JSON file declaring tools this host executes: a list of+ /// `{"name", "description", "parameters"}`. The model calls them as+ /// `host__<name>`; each call arrives as a `tool_request` on stdout and+ /// must be answered with a `tool_result` on stdin, so this requires+ /// `--input-format stream-json`+ #[arg(long, value_name = "FILE")]+ host_tools: Option<String>,},/// Run a single turn (debugging)Step {@@ -963,6 +970,7 @@ async fn handle_agent(cmd: AgentCommands) {budget,output_format,input_format,+ host_tools,} => {cli_agent_run(&project,@@ -981,6 +989,7 @@ async fn handle_agent(cmd: AgentCommands) {resume.into_request(),output_format,input_format,+ host_tools.as_deref(),).await}diff --git a/src-tauri/jan-cli/tests/stream_json_host_tools.rs b/src-tauri/jan-cli/tests/stream_json_host_tools.rsnew file mode 100644index 000000000..b99d51c44--- /dev/null+++ b/src-tauri/jan-cli/tests/stream_json_host_tools.rs@@ -0,0 +1,455 @@+//! `--host-tools` end to end, through the real binary.+//!+//! The guarantee here is about what crosses the process boundary: a declared+//! tool is advertised in the handshake, a call to it leaves as a `tool_request`+//! on stdout, and the `tool_result` the host writes to stdin becomes the tool+//! message the model sees on the next request. None of that is observable from+//! inside the process -- the printer writes to fd 1 and the reader reads fd 0 --+//! so the round trip is driven here rather than asserted one layer in.+//!+//! The provider is a stub on a loopback port: the first request is answered+//! with a tool call, the second with prose, which is the smallest exchange that+//! makes a host tool's result reach the model.++use std::io::{BufRead, BufReader, Read, Write};+use std::net::{TcpListener, TcpStream};+use std::path::PathBuf;+use std::process::{Child, Command, Output, Stdio};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use std::time::Duration;++/// The model calls the declared host tool. `host__` is the advertised name; the+/// host is told the bare one.+const TOOL_CALL: &str = concat!(+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",",+ "\"tool_calls\":[{\"index\":0,\"id\":\"call-1\",\"type\":\"function\",\"function\":",+ "{\"name\":\"host__robot_arm_move\",\"arguments\":\"{\\\"position\\\":\\\"bin\\\"}\"}}]},",+ "\"finish_reason\":null}]}\n\n",+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{},",+ "\"finish_reason\":\"tool_calls\"}],",+ "\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2,\"total_tokens\":7}}\n\n",+ "data: [DONE]\n\n",+);++/// The turn after the tool result: plain prose, which ends the run.+const ANSWER: &str = concat!(+ "data: {\"id\":\"stub-2\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",",+ "\"content\":\"the arm reached bin\"},\"finish_reason\":null}]}\n\n",+ "data: {\"id\":\"stub-2\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],",+ "\"usage\":{\"prompt_tokens\":9,\"completion_tokens\":4,\"total_tokens\":13}}\n\n",+ "data: [DONE]\n\n",+);++/// Serve `replies` in order, one per connection, repeating the last once they+/// run out. The bodies each request carried are kept so a test can assert what+/// the model was actually sent -- which is where a host tool's result has to+/// land for the round trip to mean anything.+fn stub_provider(replies: &'static [&'static str]) -> (String, Arc<std::sync::Mutex<Vec<String>>>) {+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind the stub provider");+ let addr = listener.local_addr().expect("stub address");+ let seen: Arc<std::sync::Mutex<Vec<String>>> = Arc::new(std::sync::Mutex::new(Vec::new()));+ let sink = Arc::clone(&seen);+ let nth = AtomicUsize::new(0);+ std::thread::spawn(move || {+ for stream in listener.incoming() {+ let Ok(mut stream) = stream else { continue };+ let body = read_request(&mut stream);+ sink.lock().expect("request log").push(body);+ let i = nth.fetch_add(1, Ordering::SeqCst);+ let reply = replies[i.min(replies.len() - 1)];+ let response = format!(+ "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",+ reply.len()+ );+ let _ = stream.write_all(response.as_bytes());+ let _ = stream.flush();+ }+ });+ (format!("http://{addr}/v1"), seen)+}++/// Read one request off the wire and return its body. Without draining the+/// body the client sees a reset instead of an answer, which would make a+/// failure pass for the wrong reason.+fn read_request(stream: &mut TcpStream) -> String {+ 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 String::new(),+ 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 String::from_utf8_lossy(&buf[head + 4..]).to_string();+ }+ }+}++/// A private home and data folder per test, removed on drop.+struct Scratch {+ root: PathBuf,+}++impl Scratch {+ fn new(name: &str) -> Self {+ let root = std::env::temp_dir().join(format!("jan-host-{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")+ }++ /// Write a `--host-tools` file and return its path.+ fn declare(&self, contents: &str) -> PathBuf {+ let path = self.root.join("host-tools.json");+ std::fs::write(&path, contents).expect("write the declaration");+ path+ }++ 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)+ );+ }++ 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+ }++ /// The duplex form: stdin stays open so a host can answer.+ fn spawn_duplex(&self, host_tools: &str) -> Child {+ 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",+ "--host-tools",+ host_tools,+ "--max-turns",+ "4",+ "move the arm",+ ])+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn the jan CLI")+ }+}++impl Drop for Scratch {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.root);+ }+}++/// One well-formed declaration, as a host would write it.+const DECL: &str = r#"[{"name":"robot_arm_move","description":"Move the arm.",+ "parameters":{"type":"object","properties":{"position":{"type":"string"}},+ "required":["position"]}}]"#;++fn records(out: &Output) -> Vec<serde_json::Value> {+ let stdout = String::from_utf8_lossy(&out.stdout);+ stdout+ .lines()+ .filter(|l| !l.trim().is_empty())+ .map(|line| {+ serde_json::from_str(line)+ .unwrap_or_else(|e| panic!("not one JSON object per line: {e}\n{line}"))+ })+ .collect()+}++/// The whole point of the flag: the model calls a tool this process cannot run,+/// the host runs it, and its answer reaches the model as the tool message.+///+/// Driven through the binary because every step of that sentence is a process+/// boundary -- stdout for the request, stdin for the answer, and the provider+/// request that proves the answer was actually carried into the next turn.+#[test]+fn a_declared_host_tool_round_trips_through_the_client() {+ let scratch = Scratch::new("round-trip");+ let (url, seen) = stub_provider(&[TOOL_CALL, ANSWER]);+ scratch.configure(&url);+ let decl = scratch.declare(DECL);++ let mut child = scratch.spawn_duplex(decl.to_str().expect("utf-8 path"));+ let mut stdin = child.stdin.take().expect("piped stdin");+ let stdout = BufReader::new(child.stdout.take().expect("piped stdout"));++ let mut handshake = None;+ let mut request = None;+ let mut echoed_result = false;+ for line in stdout.lines() {+ let Ok(line) = line else { break };+ if line.trim().is_empty() {+ continue;+ }+ let msg: serde_json::Value = match serde_json::from_str(&line) {+ Ok(v) => v,+ Err(_) => continue,+ };+ match msg["type"].as_str() {+ Some("init") => handshake = Some(msg),+ Some("tool_request") => {+ // Answer it exactly as a host would, then stop reading: the+ // rest of the run is the provider's to finish.+ let id = msg["request_id"].as_str().expect("a request id");+ writeln!(+ stdin,+ "{}",+ serde_json::json!({+ "type": "tool_result",+ "request_id": id,+ "content": "{\"ok\":true,\"position\":\"bin\"}",+ })+ )+ .expect("answer the request");+ stdin.flush().expect("flush the answer");+ request = Some(msg);+ }+ // The run's own view of the answer, echoed back so a client can+ // see what the model was given. Read here rather than off the+ // collected output: this loop consumes stdout, so a record after+ // the one it breaks on would never be collected.+ Some("tool_result") => echoed_result = true,+ Some("result") => break,+ _ => {}+ }+ }+ drop(stdin);+ let out = child.wait_with_output().expect("collect the run");++ let handshake = handshake.expect("the run never sent a handshake");+ assert_eq!(+ handshake["tools"]+ .as_array()+ .expect("a tool list")+ .iter()+ .filter(|t| *t == "host__robot_arm_move")+ .count(),+ 1,+ "the declared tool is advertised under its qualified name: {handshake}"+ );+ assert_eq!(+ handshake["tool_specs"][0]["function"]["name"], "host__robot_arm_move",+ "the handshake echoes the schema the host declared: {handshake}"+ );++ let request = request.expect("the model's call never reached the host");+ assert_eq!(+ request["tool_name"], "robot_arm_move",+ "the host is told the name it declared, not the prefixed one: {request}"+ );+ assert_eq!(request["args"]["position"], "bin");++ // The result has to arrive as the model's tool message, which is only+ // observable in what the provider was sent next.+ let requests = seen.lock().expect("request log");+ assert_eq!(+ requests.len(),+ 2,+ "the run did not take a second turn, so the result never reached the model"+ );+ assert!(+ requests[1].contains("\\\"position\\\":\\\"bin\\\"")+ || requests[1].contains("{\\\"ok\\\":true"),+ "the host's answer is not in the follow-up request: {}",+ requests[1]+ );+ assert!(+ echoed_result,+ "the client is never shown the result the model was given"+ );+ assert!(+ out.status.success(),+ "the round trip did not end cleanly: {}",+ String::from_utf8_lossy(&out.stderr)+ );+}++/// A call answered on stdin needs a client reading stdout, so the flag requires+/// the duplex pairing -- and the refusal is reported *on the channel*, not just+/// as a human string on stderr. A machine consumer that gets an empty stdout+/// has nothing to act on.+#[test]+fn host_tools_without_a_duplex_channel_is_refused_on_the_stream() {+ let scratch = Scratch::new("pairing");+ let decl = scratch.declare(DECL);+ let project = scratch.project();++ let out = scratch+ .command(&[+ "cli",+ "agent",+ "run",+ "--project",+ project.to_str().expect("utf-8 path"),+ "--output-format",+ "stream-json",+ "--host-tools",+ decl.to_str().expect("utf-8 path"),+ "say hi",+ ])+ .stdin(Stdio::null())+ .output()+ .expect("run the jan CLI");++ assert!(!out.status.success(), "a refused run must not exit 0");+ let records = records(&out);+ assert_eq!(+ records.len(),+ 1,+ "a setup failure is one record and no handshake: {records:?}"+ );+ assert_eq!(records[0]["type"], "result");+ assert_eq!(records[0]["is_error"], true);+ assert_eq!(records[0]["error"]["code"], "setup_error");+ assert!(+ records[0]["error"]["message"]+ .as_str()+ .expect("a message")+ .contains("--host-tools requires --input-format stream-json"),+ "the message names the flag that is wrong: {}",+ records[0]+ );+}++/// A mistyped path is the first failure a host is likely to hit, and it is+/// reported the same way: on the channel, before anything is spent.+#[test]+fn an_unreadable_declaration_is_refused_on_the_stream() {+ let scratch = Scratch::new("missing");+ let project = scratch.project();++ let out = scratch+ .command(&[+ "cli",+ "agent",+ "run",+ "--project",+ project.to_str().expect("utf-8 path"),+ "--output-format",+ "stream-json",+ "--input-format",+ "stream-json",+ "--host-tools",+ "/nonexistent/host-tools.json",+ "say hi",+ ])+ .stdin(Stdio::null())+ .output()+ .expect("run the jan CLI");++ assert!(!out.status.success());+ let records = records(&out);+ assert_eq!(records.len(), 1, "one record, no handshake: {records:?}");+ assert_eq!(records[0]["error"]["code"], "setup_error");+ assert!(+ records[0]["error"]["message"]+ .as_str()+ .expect("a message")+ .contains("cannot read --host-tools file"),+ "the message names the path that failed: {}",+ records[0]+ );+}++/// A tool named for one this process already runs is refused at declaration+/// time: the host has misunderstood whose implementation will run, and failing+/// at startup is kinder than letting it shadow a built-in for a whole session.+#[test]+fn a_reserved_name_is_refused_before_the_run_starts() {+ let scratch = Scratch::new("reserved");+ let decl = scratch.declare(r#"[{"name":"bash","description":"not yours"}]"#);+ let project = scratch.project();++ let out = scratch+ .command(&[+ "cli",+ "agent",+ "run",+ "--project",+ project.to_str().expect("utf-8 path"),+ "--output-format",+ "stream-json",+ "--input-format",+ "stream-json",+ "--host-tools",+ decl.to_str().expect("utf-8 path"),+ "say hi",+ ])+ .stdin(Stdio::null())+ .output()+ .expect("run the jan CLI");++ assert!(!out.status.success());+ let records = records(&out);+ assert_eq!(records[0]["error"]["code"], "setup_error");+ assert!(+ records[0]["error"]["message"]+ .as_str()+ .expect("a message")+ .contains("reserved"),+ "the message says the name is reserved: {}",+ records[0]+ );+}diff --git a/src-tauri/jan-cli/tests/stream_json_init.rs b/src-tauri/jan-cli/tests/stream_json_init.rsindex fd2907393..6bd718a5d 100644--- a/src-tauri/jan-cli/tests/stream_json_init.rs+++ b/src-tauri/jan-cli/tests/stream_json_init.rs@@ -217,7 +217,7 @@ fn assert_handshake(first: &serde_json::Value, project: &Path) {);assert_eq!(first["input_kinds"],- serde_json::json!(["user", "abort", "permission"]),+ serde_json::json!(["user", "abort", "permission", "tool_result"]),"a client is told what it may send back");// The caps travel with the kinds, so a client that sends an image reads the@@ -241,6 +241,10 @@ fn assert_handshake(first: &serde_json::Value, project: &Path) {}),"the advertised caps are the ones the parser enforces");+ assert!(+ first.get("tool_specs").is_none(),+ "a run that declared no host tools carries no specs: {first}"+ );}#[test]diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex eff12f80f..bab86a896 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -133,6 +133,11 @@ pub enum StreamEvent {/// concurrently. `event` is a non-terminal child event (Token/Step/ToolCall//// ToolResult/PermissionRequest); the child's terminal Done/Error is never/// wrapped (its result is delivered via `await_subagent`).+ ///+ /// Never a `ToolRequest`: a client answers a request by `request_id` on+ /// stdin, and it is told nothing about this wrapper, so a nested request+ /// would be unanswerable. `run_subagent` clears the child's host tool set+ /// rather than relying on this, which is why the case cannot arise.Subagent {run_id: String,name: String,@@ -233,6 +238,21 @@ pub enum StreamEvent {prompt_kind: String,offers_always: bool,},+ /// A host-registered tool was called and the run is waiting for the host to+ /// execute it. The client replies with a `tool_result` line carrying this+ /// `request_id`; until it does, the turn is parked on this one call.+ ///+ /// `tool_name` is the name the *host* declared, not the `host__`-prefixed+ /// name the model calls: the host dispatches on the name it chose and never+ /// has to know this layer's prefixing rule.+ ToolRequest {+ request_id: String,+ tool_name: String,+ /// The arguments the model produced, already parsed from the call's+ /// JSON string. Validated against nothing here -- the host owns the+ /// schema it declared and is the only party that can enforce it.+ args: serde_json::Value,+ },}/// A subagent in a not-yet-started phase of a phased dispatch: its name (unique@@ -564,6 +584,14 @@ pub(crate) mod tests {offers_always: true,},),+ (+ "ToolRequest",+ StreamEvent::ToolRequest {+ request_id: "host-1".into(),+ tool_name: "observe".into(),+ args: serde_json::json!({ "camera": "front" }),+ },+ ),]}@@ -596,7 +624,8 @@ pub(crate) mod tests {| StreamEvent::TurnUsage { .. }| StreamEvent::Done { .. }| StreamEvent::Error { .. }- | StreamEvent::PermissionRequest { .. } => {}+ | StreamEvent::PermissionRequest { .. }+ | StreamEvent::ToolRequest { .. } => {}}}diff --git a/src-tauri/src/core/agent/host_tools.rs b/src-tauri/src/core/agent/host_tools.rsnew file mode 100644index 000000000..0a92dd15b--- /dev/null+++ b/src-tauri/src/core/agent/host_tools.rs@@ -0,0 +1,570 @@+//! Tools a *host* process registers, and the callback that runs them.+//!+//! A plugin tool ([`tauri_plugin_agent_tools::tools::plugin_tools`]) is a+//! command this process spawns: arguments on stdin, stdout as the result. That+//! covers a tool someone can package as an executable, but not a tool whose+//! implementation lives in the caller -- a robot arm behind a Python host, an+//! editor's own buffer, a device only the host has a handle to. Those cannot be+//! a subprocess of this process, because the state they act on is not here.+//!+//! So a host tool is the inverse arrangement: the host declares the schema up+//! front, and when the model calls it the run emits a+//! [`StreamEvent::ToolRequest`](crate::core::agent::events::StreamEvent::ToolRequest)+//! and *waits* for the host to send a `tool_result` back on stdin. The+//! correlation is the same one-shot registry the permission prompt uses, for+//! the same reason: exactly one answer per request, and a client that goes away+//! must not park a turn forever.+//!+//! What this module does not do is decide policy. A host tool is treated+//! exactly as a plugin or MCP tool is -- prompted rather than auto-allowed, and+//! withheld entirely in read-only Plan mode -- because its capability is just as+//! opaque from here. That default is the shipped answer to "what class does an+//! undeclared tool land in", and a host tool that mutates the physical world is+//! the case it was written for.++use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Arc;++use serde::{Deserialize, Serialize};+use tokio::sync::{oneshot, Mutex};++/// Prefix every host tool's advertised name carries, so a host cannot shadow a+/// built-in (`bash`, `read`) or collide with a plugin or MCP tool. Mirrors+/// `plugin_tools::NAME_PREFIX`; the model sees the qualified name and calls it+/// by that.+///+/// The dispatcher tests this prefix before reaching MCP, so an MCP tool that is+/// itself named `host__x` is shadowed by a declared host tool of the same name.+/// That is the same precedence the `plugin__` convention already has, and it+/// resolves in favour of the party that declared the name for this run.+pub const NAME_PREFIX: &str = "host__";++/// Cap on the advertised `host__<name>` name. Several providers reject a+/// function name past 64 characters, and they reject the *request* rather than+/// just the tool, so one over-long name would break every call in the run.+const MAX_NAME_LEN: usize = 64;++/// Cap on how many tools one host may declare. Generous next to any real tool+/// set; it exists so a malformed or generated file cannot put an unbounded+/// number of schemas into every request's prefix.+const MAX_HOST_TOOLS: usize = 128;++static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1);++/// What a host tool call is answered with. The host sends this back keyed by+/// the request id; `is_error` marks a failure the model should see as one+/// without ending the turn.+#[derive(Clone, Debug, Eq, PartialEq)]+pub(crate) struct HostToolResult {+ pub content: String,+ pub is_error: bool,+}++/// Why a host tool call produced no answer from the host.+#[derive(Clone, Debug, Eq, PartialEq)]+pub(crate) enum HostToolError {+ /// The client disconnected, or the run ended, before answering.+ ClientGone,+}++pub(crate) type HostToolOutcome = Result<HostToolResult, HostToolError>;++/// In-flight host tool calls keyed by request id, shared between the loop+/// (which inserts a one-shot sender before awaiting) and the input reader+/// (which removes and resolves it).+pub(crate) type HostToolRegistry = Arc<Mutex<HashMap<String, oneshot::Sender<HostToolOutcome>>>>;++pub(crate) fn new_registry() -> HostToolRegistry {+ Arc::new(Mutex::new(HashMap::new()))+}++/// Reserve a request id and the channel its answer arrives on.+pub(crate) async fn register(registry: &HostToolRegistry) -> (String, oneshot::Receiver<HostToolOutcome>) {+ let id = format!("host-{}", NEXT_REQUEST_ID.fetch_add(1, Ordering::Relaxed));+ let (sender, receiver) = oneshot::channel();+ registry.lock().await.insert(id.clone(), sender);+ (id, receiver)+}++/// Answer a pending call. Taking the sender is what makes an answer single-use:+/// a second `tool_result` for the same id finds nothing and is reported to the+/// client, rather than silently replacing a result the run already acted on.+pub(crate) async fn respond(+ registry: &HostToolRegistry,+ request_id: &str,+ outcome: HostToolOutcome,+) -> Result<(), String> {+ let sender = registry+ .lock()+ .await+ .remove(request_id)+ .ok_or_else(|| format!("no host tool request '{request_id}' is pending"))?;+ sender+ .send(outcome)+ .map_err(|_| format!("host tool request '{request_id}' is no longer pending"))+}++/// Fail one pending call closed. Used for a request raised *after* the client+/// left: `strand_all` runs once when stdin closes, so a later call would+/// otherwise wait on a reader that no longer exists.+pub(crate) async fn strand(registry: &HostToolRegistry, request_id: &str) {+ let sender = registry.lock().await.remove(request_id);+ if let Some(sender) = sender {+ let _ = sender.send(Err(HostToolError::ClientGone));+ }+}++/// Fail every pending call closed. Called when the client's stdin closes: a+/// host that cannot answer must not leave the turn parked on a reply that can+/// never arrive.+pub(crate) async fn strand_all(registry: &HostToolRegistry) {+ let pending = std::mem::take(&mut *registry.lock().await);+ for (_, sender) in pending {+ let _ = sender.send(Err(HostToolError::ClientGone));+ }+}++/// One tool as the host declares it.+///+/// Unknown keys are rejected rather than ignored, via `unknown` below rather+/// than serde's `deny_unknown_fields`: this type is deserialized from the+/// `jan-cli` crate, which resolves its own lockfile, and the attribute expands+/// to code bound to a `serde_core` that crate's graph has two copies of.+/// Collecting the surplus keys instead needs nothing outside `serde_json`.+///+/// Validating the set at startup is the whole point of declaring it up front: a+/// misspelled `paramters` that parsed would silently register the+/// empty-argument schema, the model would be told the tool takes nothing, and+/// the mistake would surface as a call with no arguments rather than as the+/// typo it is.+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]+pub struct HostToolDecl {+ pub name: String,+ #[serde(default)]+ pub description: String,+ /// JSON Schema for the tool's arguments, passed to the provider verbatim.+ #[serde(default)]+ pub parameters: Option<serde_json::Value>,+ /// Every key that is none of the above, kept only so `declare` can refuse+ /// it by name. Never serialized back: a declaration this process re-emits+ /// is the set it accepted, which by then has no unknown keys.+ #[serde(flatten, default, skip_serializing)]+ pub unknown: std::collections::BTreeMap<String, serde_json::Value>,+}++/// A registered host tool.+#[derive(Clone, Debug, PartialEq, Serialize)]+pub struct HostTool {+ /// The name the model calls, already prefixed (`host__<name>`).+ pub qualified_name: String,+ /// The name the *host* used. `tool_request` carries this, not the qualified+ /// name: the host asked for `observe` and must be able to dispatch on+ /// `observe` without knowing this layer's prefixing rule.+ pub name: String,+ pub description: String,+ pub parameters: serde_json::Value,+}++impl HostTool {+ /// The OpenAI tool schema advertised for this tool.+ ///+ /// The host's `parameters` are embedded unchanged. That is deliberate and it+ /// is the whole point of R5 in the contract: a host compares the schema it+ /// gets back against the one it sent, so a normalization pass here -- even a+ /// well-meaning one that fills in a missing `type` -- would make that+ /// comparison fail and silently drop constraints like `minItems` that the+ /// host is relying on for validation.+ pub fn schema(&self) -> serde_json::Value {+ serde_json::json!({+ "type": "function",+ "function": {+ "name": self.qualified_name,+ "description": self.description,+ "parameters": self.parameters,+ }+ })+ }+}++/// Why a declaration was refused. A host tool set is rejected as a whole rather+/// than silently pruned: a host that asked for four tools and got three would+/// discover it at the first call, mid-task, instead of at startup.+#[derive(Clone, Debug, PartialEq)]+pub enum DeclError {+ EmptyName,+ UnsafeName(String),+ NameTooLong(String),+ Reserved(String),+ Duplicate(String),+ NonObjectSchema(String),+ TooMany(usize),+ UnknownKey(String, String),+}++impl std::fmt::Display for DeclError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ DeclError::EmptyName => write!(f, "a host tool has an empty name"),+ DeclError::UnsafeName(n) => write!(+ f,+ "host tool name '{n}' must be ASCII letters, digits, '_' or '-' and cannot contain '__'"+ ),+ DeclError::NameTooLong(n) => write!(+ f,+ "host tool name '{n}' is too long: '{NAME_PREFIX}{n}' exceeds {MAX_NAME_LEN} characters"+ ),+ DeclError::Reserved(n) => {+ write!(f, "host tool name '{n}' is reserved by a built-in tool")+ }+ DeclError::Duplicate(n) => write!(f, "host tool name '{n}' is declared twice"),+ DeclError::NonObjectSchema(n) => write!(+ f,+ "host tool '{n}' parameters must be a JSON Schema object"+ ),+ DeclError::TooMany(n) => write!(+ f,+ "{n} host tools declared, more than the {MAX_HOST_TOOLS} a run accepts"+ ),+ DeclError::UnknownKey(n, key) => write!(+ f,+ "host tool '{n}' has an unknown field '{key}' (expected name, description, parameters)"+ ),+ }+ }+}++/// Every host tool a run may call, keyed by qualified name.+#[derive(Clone, Debug, Default, PartialEq, Serialize)]+pub struct HostToolSet {+ tools: Vec<HostTool>,+}++impl HostToolSet {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn is_empty(&self) -> bool {+ self.tools.is_empty()+ }++ pub fn len(&self) -> usize {+ self.tools.len()+ }++ pub fn all(&self) -> &[HostTool] {+ &self.tools+ }++ pub fn get(&self, qualified_name: &str) -> Option<&HostTool> {+ self.tools+ .iter()+ .find(|t| t.qualified_name == qualified_name)+ }++ /// Whether `name` is a host tool. Cheap enough for the dispatcher's hot+ /// path, and false for every built-in, plugin and MCP name by construction.+ pub fn is_host_tool(&self, name: &str) -> bool {+ name.starts_with(NAME_PREFIX) && self.get(name).is_some()+ }++ pub fn schemas(&self) -> Vec<serde_json::Value> {+ self.tools.iter().map(HostTool::schema).collect()+ }++ /// Validate and register a host's declarations, rejecting the whole set on+ /// the first problem.+ pub fn declare(entries: Vec<HostToolDecl>) -> Result<Self, DeclError> {+ // Every schema is repeated in the cached prefix of every request for+ // the whole run, so an oversized set is paid for per turn rather than+ // once. Capped for the same reason the channel caps images and line+ // length: a declaration file is host input, and unbounded host input+ // with a per-turn cost is a way to make a run expensive by accident.+ if entries.len() > MAX_HOST_TOOLS {+ return Err(DeclError::TooMany(entries.len()));+ }+ let mut set = Self::new();+ for entry in entries {+ let name = entry.name.trim().to_string();+ if name.is_empty() {+ return Err(DeclError::EmptyName);+ }+ // Before anything else about the tool: a key this parser does not+ // know is a typo in the host's file, and guessing which field was+ // meant would register a tool the host did not describe.+ if let Some(key) = entry.unknown.keys().next() {+ return Err(DeclError::UnknownKey(name, key.clone()));+ }+ if !is_safe_name(&name) {+ return Err(DeclError::UnsafeName(name));+ }+ let qualified_name = format!("{NAME_PREFIX}{name}");+ if qualified_name.len() > MAX_NAME_LEN {+ return Err(DeclError::NameTooLong(name));+ }+ // A host tool is prefixed, so it cannot collide with a built-in on+ // the wire. The check is on the *bare* name anyway: a host that+ // registers `bash` or `read` has almost certainly misunderstood+ // whose implementation will run, and failing at startup is kinder+ // than letting it call its own sandbox for a whole session.+ if is_reserved(&name) {+ return Err(DeclError::Reserved(name));+ }+ if set.get(&qualified_name).is_some() {+ return Err(DeclError::Duplicate(name));+ }+ let parameters = entry.parameters.unwrap_or_else(empty_schema);+ if !parameters.is_object() {+ return Err(DeclError::NonObjectSchema(name));+ }+ set.tools.push(HostTool {+ qualified_name,+ name,+ description: entry.description.trim().to_string(),+ parameters,+ });+ }+ Ok(set)+ }+}++/// The schema for a tool that declares no parameters.+fn empty_schema() -> serde_json::Value {+ serde_json::json!({ "type": "object", "properties": {} })+}++/// Names a host may not take. Built-ins plus the agent's own session tools:+/// every name this process would otherwise dispatch itself.+fn is_reserved(name: &str) -> bool {+ tauri_plugin_agent_tools::tools::lookup(name).is_some()+ || name == tauri_plugin_agent_tools::tools::monitor::MONITOR_TOOL_NAME+ || matches!(name, "ask" | "todo")+ || crate::core::agent::subagent::is_subagent_tool(name)+}++/// Host tool names are restricted to what every provider accepts in a function+/// name and what cannot be confused with the `__` qualifier separator. A host+/// whose internal name is outside this set maps it on its own side and maps it+/// back on the result, which is what the reference consumer already does.+fn is_safe_name(name: &str) -> bool {+ !name.is_empty()+ && !name.contains("__")+ && name+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn decl(name: &str) -> HostToolDecl {+ HostToolDecl {+ name: name.to_string(),+ description: "does a thing".to_string(),+ parameters: None,+ unknown: Default::default(),+ }+ }++ #[test]+ fn a_declared_tool_is_advertised_under_a_qualified_name() {+ let set = HostToolSet::declare(vec![decl("observe")]).expect("declares");+ assert_eq!(set.len(), 1);+ let tool = &set.all()[0];+ assert_eq!(tool.qualified_name, "host__observe");+ // The host's own name survives alongside it: tool_request carries this.+ assert_eq!(tool.name, "observe");+ assert!(set.is_host_tool("host__observe"));+ // A bare name is not a host tool: the model only ever sees the prefix.+ assert!(!set.is_host_tool("observe"));+ }++ #[test]+ fn the_host_schema_is_advertised_byte_for_byte() {+ // R5: the host compares what it gets back to what it sent. Constraints+ // a normalizer would strip or add are exactly what this pins.+ let parameters = json!({+ "type": "object",+ "properties": {+ "joints": {+ "type": "array",+ "items": { "type": "number" },+ "minItems": 6,+ "maxItems": 6+ },+ "when": { "type": "string", "format": "date-time" }+ },+ "required": ["joints"],+ "additionalProperties": false+ });+ let set = HostToolSet::declare(vec![HostToolDecl {+ name: "move_arm".to_string(),+ description: "move".to_string(),+ parameters: Some(parameters.clone()),+ unknown: Default::default(),+ }])+ .expect("declares");+ assert_eq!(set.all()[0].schema()["function"]["parameters"], parameters);+ }++ #[test]+ fn a_tool_with_no_parameters_gets_an_empty_object_schema() {+ let set = HostToolSet::declare(vec![decl("observe")]).expect("declares");+ assert_eq!(+ set.all()[0].parameters,+ json!({ "type": "object", "properties": {} })+ );+ }++ #[test]+ fn a_duplicate_name_is_rejected_not_replaced() {+ // R3: rejected, never silently resolved. A host that declared two tools+ // and got one would find out at the first call.+ let err = HostToolSet::declare(vec![decl("observe"), decl("observe")])+ .expect_err("duplicate refused");+ assert_eq!(err, DeclError::Duplicate("observe".to_string()));+ }++ /// A declaration file is host input whose cost is paid in every request's+ /// prefix, so the set is bounded like the channel's other host input.+ #[test]+ fn an_oversized_declaration_is_refused() {+ let entries: Vec<HostToolDecl> = (0..=MAX_HOST_TOOLS)+ .map(|i| decl(&format!("tool_{i}")))+ .collect();+ let n = entries.len();+ assert_eq!(HostToolSet::declare(entries), Err(DeclError::TooMany(n)));++ // The cap itself is allowed: the boundary is inclusive, so a host that+ // declares exactly the limit is not refused.+ let entries: Vec<HostToolDecl> = (0..MAX_HOST_TOOLS)+ .map(|i| decl(&format!("tool_{i}")))+ .collect();+ assert_eq!(+ HostToolSet::declare(entries).expect("the cap is allowed").len(),+ MAX_HOST_TOOLS+ );+ }++ /// Validating the set up front is the point of declaring it, so a key the+ /// parser does not know is a mistake to report rather than to drop. A+ /// misspelled `parameters` would otherwise register the empty schema and+ /// tell the model the tool takes no arguments.+ #[test]+ fn an_unknown_key_in_a_declaration_is_refused() {+ let decl: HostToolDecl = serde_json::from_str(+ r#"{"name":"observe","description":"d","paramters":{"type":"object"}}"#,+ )+ .expect("the surplus key is collected, not a parse error");+ assert_eq!(+ HostToolSet::declare(vec![decl]),+ Err(DeclError::UnknownKey(+ "observe".to_string(),+ "paramters".to_string()+ ))+ );++ // And the schema really would have been lost: the typo means+ // `parameters` never arrived, so accepting it would advertise a tool+ // that takes no arguments at all.+ let decl: HostToolDecl =+ serde_json::from_str(r#"{"name":"observe","paramters":{"type":"object"}}"#)+ .expect("parses");+ assert_eq!(decl.parameters, None);+ }++ #[test]+ fn reserved_names_are_refused() {+ for name in [+ "bash",+ "read",+ "edit",+ "monitor",+ "ask",+ "todo",+ "dispatch_subagent",+ ] {+ let err = HostToolSet::declare(vec![decl(name)]);+ assert_eq!(+ err,+ Err(DeclError::Reserved(name.to_string())),+ "'{name}' must be reserved"+ );+ }+ }++ #[test]+ fn an_unsafe_name_is_refused() {+ for name in ["yam.move_ee_ik", "has space", "unicode\u{00e9}", "a__b"] {+ assert_eq!(+ HostToolSet::declare(vec![decl(name)]),+ Err(DeclError::UnsafeName(name.to_string())),+ "'{name}' must be refused"+ );+ }+ }++ #[test]+ fn an_empty_name_is_refused() {+ assert_eq!(+ HostToolSet::declare(vec![decl(" ")]),+ Err(DeclError::EmptyName)+ );+ }++ #[test]+ fn an_over_long_name_is_refused() {+ let long = "t".repeat(MAX_NAME_LEN);+ assert_eq!(+ HostToolSet::declare(vec![decl(&long)]),+ Err(DeclError::NameTooLong(long))+ );+ }++ #[test]+ fn a_non_object_schema_is_refused() {+ let err = HostToolSet::declare(vec![HostToolDecl {+ name: "observe".to_string(),+ description: String::new(),+ parameters: Some(json!("string")),+ unknown: Default::default(),+ }]);+ assert_eq!(err, Err(DeclError::NonObjectSchema("observe".to_string())));+ }++ #[tokio::test]+ async fn an_answer_is_single_use() {+ let registry = new_registry();+ let (id, receiver) = register(®istry).await;+ let result = HostToolResult {+ content: "ok".to_string(),+ is_error: false,+ };+ respond(®istry, &id, Ok(result.clone()))+ .await+ .expect("first answer lands");+ assert_eq!(receiver.await.expect("delivered"), Ok(result));+ // A second answer for the same id has nothing to resolve and is+ // reported, rather than overwriting a result the run already used.+ assert!(respond(®istry, &id, Ok(HostToolResult {+ content: "again".to_string(),+ is_error: false,+ }))+ .await+ .is_err());+ }++ #[tokio::test]+ async fn a_disconnecting_client_strands_pending_calls_closed() {+ let registry = new_registry();+ let (_id, receiver) = register(®istry).await;+ strand_all(®istry).await;+ assert_eq!(+ receiver.await.expect("delivered"),+ Err(HostToolError::ClientGone)+ );+ }+}diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 44e6070b5..4072aaa4b 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -71,6 +71,13 @@ pub(crate) struct OrchestrationArgs {pub permissions: tauri_plugin_agent_tools::permissions::ToolPermissions,pub project_root: Option<std::path::PathBuf>,pub permission_requests: PermissionRegistry,+ /// Tools a host process registered for this run, and the registry their+ /// calls are answered through. Only a client on the headless stdio channel+ /// can execute one, so these exist only in that build.+ #[cfg(feature = "cli")]+ pub host_tools: crate::core::agent::host_tools::HostToolSet,+ #[cfg(feature = "cli")]+ pub host_tool_requests: crate::core::agent::host_tools::HostToolRegistry,/// Present only when a client can render and answer structured questions.pub ask_requests: Option<crate::core::agent::interaction::AskRegistry>,/// Session's canonical todo list. Present for the top-level run only;@@ -417,6 +424,15 @@ struct CompositeToolInvoker {/// `execute_builtin`: they are not built-ins, and like MCP tools their/// capability is unknowable, so they are prompted and hidden in Plan mode.plugin_tools: tauri_plugin_agent_tools::tools::plugin_tools::PluginToolSet,+ /// Tools a host process declared for this run, and the registry their calls+ /// are answered through. Unlike every other tool here, these do not execute+ /// in this process at all: the call goes out as a `tool_request` and the+ /// host sends the result back. Empty on every surface but a duplex headless+ /// run, since nothing else has a peer that could answer.+ #[cfg(feature = "cli")]+ host_tools: crate::core::agent::host_tools::HostToolSet,+ #[cfg(feature = "cli")]+ host_tool_requests: crate::core::agent::host_tools::HostToolRegistry,/// `context` answers and failure notices raised by hooks during this run,/// drained into `<SYSTEM>` reminders alongside the monitor's. `Arc` because/// the tool-event hooks fire inside the toolset and report through a sink@@ -851,8 +867,93 @@ impl CompositeToolInvoker {outcome.denied}+ /// Whether `name` is a tool the client executes. Always `false` where there+ /// is no client: the desktop build has no peer that could answer one.+ fn is_host_tool(&self, name: &str) -> bool {+ #[cfg(feature = "cli")]+ {+ self.host_tools.is_host_tool(name)+ }+ #[cfg(not(feature = "cli"))]+ {+ let _ = name;+ false+ }+ }++ /// Hand a host tool call to the client and wait for its answer.+ ///+ /// The returned string is what the model sees, in every outcome: a host+ /// that fails, or one that goes away mid-call, still produces a tool+ /// message. An unanswered call would otherwise leave the conversation with+ /// an assistant turn whose call is never resolved, which is not a state the+ /// run can be resumed from.+ #[cfg(feature = "cli")]+ async fn call_host_tool(&self, name: &str, args: &serde_json::Value) -> String {+ let Some(tool) = self.host_tools.get(name) else {+ return format!("ERROR: host tool '{name}' is not registered");+ };+ // The same hook bracket the plugin path fires, for the same reason: a+ // host tool is still a tool call, and a PreToolUse policy that could+ // not see it would have a hole exactly where a third party's code runs.+ let payload = tauri_plugin_agent_tools::tools::hooks::HookPayload {+ tool_name: Some(name.to_string()),+ tool_input: Some(args.clone()),+ ..Default::default()+ };+ if let Some(reason) = self+ .fire_hooks(+ tauri_plugin_agent_tools::tools::hooks::HookEvent::PreToolUse,+ payload.clone(),+ )+ .await+ {+ return hook_denied_msg(name, &reason);+ }+ let (request_id, receiver) =+ crate::core::agent::host_tools::register(&self.host_tool_requests).await;+ // The host declared `observe` and dispatches on `observe`; the `host__`+ // prefix is this layer's business, not the host's.+ let _ = self.events.send(StreamEvent::ToolRequest {+ request_id: request_id.clone(),+ tool_name: tool.name.clone(),+ args: args.clone(),+ });+ let content = match receiver.await {+ Ok(Ok(result)) => {+ if result.is_error {+ format!("ERROR: {}", result.content)+ } else {+ result.content+ }+ }+ // Stranded by a closed pipe, or the sender dropped with the run.+ Ok(Err(crate::core::agent::host_tools::HostToolError::ClientGone)) | Err(_) => {+ self.host_tool_requests.lock().await.remove(&request_id);+ format!("ERROR: host tool '{}' was not answered: the client is gone", tool.name)+ }+ };+ self.fire_hooks(+ tauri_plugin_agent_tools::tools::hooks::HookEvent::PostToolUse,+ tauri_plugin_agent_tools::tools::hooks::HookPayload {+ tool_result: Some(content.clone()),+ ..payload+ },+ )+ .await;+ content+ }+/// Prompt the user to approve an MCP tool call, mirroring the built-in gate./// A dropped responder (client gone / run cancelled) resolves to Deny.+ ///+ /// Plugin and host tools are prompted through here too: `prompt_kind` is+ /// `"mcp"` for all three because it names the *class* a consumer renders --+ /// an opaque third-party capability -- not which subsystem runs the call.+ /// The `tool_name` is the qualified one the model called (`host__move`),+ /// which is what a user needs to see; note that the matching `tool_request`+ /// carries the host's bare name (`move`) instead, since the host dispatches+ /// on the name it declared.async fn prompt_mcp_permission(&self, tool_name: &str) -> PermissionDecision {let request_id = next_permission_id();let (tx, rx) = tokio::sync::oneshot::channel();@@ -1508,6 +1609,63 @@ impl ToolInvoker for CompositeToolInvoker {out.push(ToolOutcome::plain(id, content));continue;}+ // Host tools execute in the client, not here. Dispatched on the+ // same terms as a plugin or MCP tool -- opaque capability, so+ // prompted and withheld in Plan mode -- but the call leaves the+ // process instead of running in it. `is_host_tool` is constant+ // `false` off the headless build, which has no client to ask.+ if self.is_host_tool(name) {+ let id = tc+ .get("id")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();+ if self.run_mode == crate::core::agent::plan::RunMode::Plan {+ out.push(ToolOutcome::plain(id, plan_mode_read_only_msg(name)));+ continue;+ }+ if self.permissions.is_denied(name) {+ out.push(ToolOutcome::plain(+ id,+ denied_by_policy_msg(name, &self.project_root),+ ));+ continue;+ }+ let args: serde_json::Value = tc+ .get("function")+ .and_then(|f| f.get("arguments"))+ .and_then(|v| v.as_str())+ .and_then(|s| serde_json::from_str(s).ok())+ .unwrap_or(serde_json::Value::Object(Default::default()));+ let approved = self.auto_approve+ || self.grants.lock().unwrap().covers_mcp(name)+ || match self.prompt_mcp_permission(name).await {+ PermissionDecision::AllowOnce => true,+ PermissionDecision::AllowAlways => {+ self.grants.lock().unwrap().grant_mcp(name);+ true+ }+ PermissionDecision::Deny => false,+ };+ if !approved {+ out.push(ToolOutcome::plain(+ id,+ format!("ERROR: tool '{name}' denied by user"),+ ));+ continue;+ }+ #[cfg(feature = "cli")]+ let content = self.call_host_tool(name, &args).await;+ // Unreachable off the headless build, where `is_host_tool` is+ // constant `false`.+ #[cfg(not(feature = "cli"))]+ let content = {+ let _ = &args;+ String::new()+ };+ out.push(ToolOutcome::plain(id, content));+ continue;+ }// Plugin-declared tools are dispatched ahead of the MCP fallback:// they are neither built-ins nor MCP, but their capability is just// as opaque, so they get the MCP treatment -- prompted rather than@@ -2043,6 +2201,7 @@ fn advertise_local_tools(max_parallel_subagents: u32,ask_enabled: bool,todo_enabled: bool,+ #[cfg(feature = "cli")] host_tools: &crate::core::agent::host_tools::HostToolSet,) {let planning = run_mode == crate::core::agent::plan::RunMode::Plan;if project_root.is_some() {@@ -2145,6 +2304,24 @@ fn advertise_local_tools(if todo_enabled && allowed_names.is_none_or(|allowed| allowed.contains("todo")) {openai_tools.push(crate::core::agent::todo::todo_tool_schema());}+ // Host tools run in the client, not here, so they need no project root --+ // like `ask` and `todo` they are advertised independent of that gate. What+ // they do share with plugin and MCP tools is an opaque capability, so they+ // are withheld entirely in read-only Plan mode and honor the deny list.+ #[cfg(feature = "cli")]+ if !planning {+ for tool in host_tools.all() {+ if permissions.is_denied(&tool.qualified_name) {+ continue;+ }+ if let Some(allow) = allowed_names {+ if !allow.contains(&tool.qualified_name) {+ continue;+ }+ }+ openai_tools.push(tool.schema());+ }+ }}/// The last completion of a run stopped by its money ceiling, rewritten into a@@ -2308,6 +2485,7 @@ pub(crate) async fn context_advertised_tools(max_parallel_subagents: u32,ask_enabled: bool,todo_enabled: bool,+ host_tools: &crate::core::agent::host_tools::HostToolSet,) -> Vec<serde_json::Value> {let (mut tools, mut tool_to_server) =crate::core::agent::upstream::collect_mcp_openai_tools(mcp_servers, mcp_settings)@@ -2328,6 +2506,7 @@ pub(crate) async fn context_advertised_tools(max_parallel_subagents,ask_enabled,todo_enabled,+ host_tools,);tools}@@ -2428,6 +2607,10 @@ async fn orchestrate_inner(permissions,project_root,permission_requests,+ #[cfg(feature = "cli")]+ host_tools,+ #[cfg(feature = "cli")]+ host_tool_requests,ask_requests,todo_registry,system_prompt_override,@@ -2677,6 +2860,8 @@ async fn orchestrate_inner(*max_parallel_subagents,ask_requests.is_some(),todo_registry.is_some(),+ #[cfg(feature = "cli")]+ host_tools,);let (upstream_url, session_api_keys) = resolve_upstream_for_model(@@ -2791,6 +2976,10 @@ async fn orchestrate_inner(// flight is judged by.hooks: crate::core::agent::hooks_config::resolve_hooks(root),plugin_tools: crate::core::agent::hooks_config::resolve_plugin_tools(root),+ #[cfg(feature = "cli")]+ host_tools: host_tools.clone(),+ #[cfg(feature = "cli")]+ host_tool_requests: host_tool_requests.clone(),hook_notices_queue: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),bg_shells: session_bg_shells.clone().unwrap_or_default(),};@@ -7034,6 +7223,10 @@ mod tests {run_mode: crate::core::agent::plan::RunMode::Normal,hooks: tauri_plugin_agent_tools::tools::hooks::HookSet::new(),plugin_tools: tauri_plugin_agent_tools::tools::plugin_tools::PluginToolSet::new(),+ #[cfg(feature = "cli")]+ host_tools: crate::core::agent::host_tools::HostToolSet::new(),+ #[cfg(feature = "cli")]+ host_tool_requests: crate::core::agent::host_tools::new_registry(),hook_notices_queue: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),bg_shells: std::sync::Arc::new(crate::core::agent::bg_shell::BackgroundShells::default(),@@ -7418,6 +7611,215 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A stub host: answers the run's `tool_request` the way a client on stdin+ /// would, and reports what it was asked. Spawned before the call because+ /// the dispatch parks until it replies.+ #[cfg(feature = "cli")]+ fn stub_host(+ registry: crate::core::agent::host_tools::HostToolRegistry,+ mut events: mpsc::UnboundedReceiver<StreamEvent>,+ reply: Result<crate::core::agent::host_tools::HostToolResult, ()>,+ ) -> tokio::task::JoinHandle<(String, serde_json::Value)> {+ tokio::spawn(async move {+ while let Some(ev) = events.recv().await {+ if let StreamEvent::ToolRequest {+ request_id,+ tool_name,+ args,+ } = ev+ {+ match reply {+ Ok(result) => {+ crate::core::agent::host_tools::respond(+ ®istry,+ &request_id,+ Ok(result),+ )+ .await+ .expect("the run is waiting on this id");+ }+ // The host went away mid-call.+ Err(()) => {+ crate::core::agent::host_tools::strand_all(®istry).await;+ }+ }+ return (tool_name, args);+ }+ }+ panic!("the run never emitted a tool_request");+ })+ }++ #[cfg(feature = "cli")]+ fn host_invoker(+ root: std::path::PathBuf,+ tools: crate::core::agent::host_tools::HostToolSet,+ ) -> (CompositeToolInvoker, mpsc::UnboundedReceiver<StreamEvent>) {+ let (tx, rx) = mpsc::unbounded_channel();+ let mut invoker = build_prompting_invoker(root, tx, PermissionRegistry::default());+ invoker.sandbox = false;+ invoker.auto_approve = true;+ invoker.host_tools = tools;+ (invoker, rx)+ }++ #[cfg(feature = "cli")]+ fn host_tool_set(names: &[&str]) -> crate::core::agent::host_tools::HostToolSet {+ crate::core::agent::host_tools::HostToolSet::declare(+ names+ .iter()+ .map(|n| crate::core::agent::host_tools::HostToolDecl {+ name: n.to_string(),+ description: String::new(),+ parameters: None,+ unknown: Default::default(),+ })+ .collect(),+ )+ .expect("the test names are valid")+ }++ /// R1 end to end: the call leaves as a `tool_request` carrying the host's+ /// own name, and the host's answer comes back as the tool message content.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_host_tool_call_round_trips_through_the_client() {+ let root = hooks_root("hosttoolroundtrip");+ let (invoker, events) = host_invoker(root.clone(), host_tool_set(&["observe"]));+ let host = stub_host(+ invoker.host_tool_requests.clone(),+ events,+ Ok(crate::core::agent::host_tools::HostToolResult {+ content: "two cameras, both clear".to_string(),+ is_error: false,+ }),+ );++ let out = invoker+ .invoke(&[hooked_tool_call(+ "host__observe",+ r#"{"camera":"front"}"#,+ )])+ .await+ .unwrap();++ let (asked_name, asked_args) = host.await.expect("the stub host ran");+ // The host declared `observe` and is asked for `observe`: the `host__`+ // prefix is this layer's business and never reaches the host.+ assert_eq!(asked_name, "observe");+ assert_eq!(asked_args, json!({ "camera": "front" }));+ assert_eq!(out[0].content, "two cameras, both clear");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A host tool that failed is still an answer: the model is told, and the+ /// turn continues rather than ending on it.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_failed_host_tool_result_reaches_the_model_as_an_error() {+ let root = hooks_root("hosttoolerror");+ let (invoker, events) = host_invoker(root.clone(), host_tool_set(&["command"]));+ let host = stub_host(+ invoker.host_tool_requests.clone(),+ events,+ Ok(crate::core::agent::host_tools::HostToolResult {+ content: "arm is estopped".to_string(),+ is_error: true,+ }),+ );++ let out = invoker+ .invoke(&[hooked_tool_call("host__command", "{}")])+ .await+ .unwrap();++ host.await.expect("the stub host ran");+ assert_eq!(out[0].content, "ERROR: arm is estopped");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The wedge: a host that dies mid-call must settle the turn, not park it.+ /// An unanswered call would leave an assistant turn whose call is never+ /// resolved, which is not a conversation the run can be resumed from.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_host_that_leaves_mid_call_settles_the_turn() {+ let root = hooks_root("hosttoolgone");+ let (invoker, events) = host_invoker(root.clone(), host_tool_set(&["observe"]));+ let host = stub_host(invoker.host_tool_requests.clone(), events, Err(()));++ let out = invoker+ .invoke(&[hooked_tool_call("host__observe", "{}")])+ .await+ .unwrap();++ host.await.expect("the stub host ran");+ assert!(+ out[0].content.contains("was not answered"),+ "{}",+ out[0].content+ );+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Host tools carry an opaque capability, so they get the plugin/MCP+ /// treatment: withheld entirely in read-only Plan mode, and never dispatched+ /// to the host at all.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_host_tool_is_withheld_in_plan_mode() {+ let root = hooks_root("hosttoolplan");+ let (mut invoker, mut events) = host_invoker(root.clone(), host_tool_set(&["command"]));+ invoker.run_mode = crate::core::agent::plan::RunMode::Plan;++ let out = invoker+ .invoke(&[hooked_tool_call("host__command", "{}")])+ .await+ .unwrap();++ assert!(+ out[0].content.contains("plan_mode_read_only"),+ "{}",+ out[0].content+ );+ assert!(+ !matches!(events.try_recv(), Ok(StreamEvent::ToolRequest { .. })),+ "a withheld tool must not reach the host"+ );+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The hook bracket covers host tools for the same reason it covers plugin+ /// tools: a PreToolUse policy that could not see them would have a hole+ /// exactly where a third party's code runs.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_hook_can_deny_a_host_tool() {+ let root = hooks_root("hosttooldeny");+ let (mut invoker, mut events) = host_invoker(root.clone(), host_tool_set(&["command"]));+ invoker.hooks = hook_set(vec![hook_entry(+ "PreToolUse",+ Some("host__*"),+ r#"echo '{"decision":"deny","reason":"actuators are off"}'"#,+ )]);++ let out = invoker+ .invoke(&[hooked_tool_call("host__command", "{}")])+ .await+ .unwrap();++ assert!(+ out[0].content.contains("actuators are off"),+ "{}",+ out[0].content+ );+ assert!(+ !matches!(events.try_recv(), Ok(StreamEvent::ToolRequest { .. })),+ "a hook-denied tool must not reach the host"+ );+ let _ = std::fs::remove_dir_all(&root);+ }+/// The three session-lifecycle events go through `fire_hooks` rather than/// the toolset's `execute_builtin` bracket, so they are pinned here: each/// fires, each receives its payload, and each is still live in Plan modediff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex 635bae085..3d9fdc659 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -27,6 +27,11 @@ pub mod global_config;#[cfg(feature = "cli")]pub mod goal;pub mod hooks_config;+// Host tools are executed by a client over the headless stdio channel, so the+// capability exists only where that channel does. The desktop build has no peer+// that could answer a `tool_request`.+#[cfg(feature = "cli")]+pub mod host_tools;pub mod interaction;pub mod r#loop;pub mod memory;diff --git a/src-tauri/src/core/agent/prefix_stability.rs b/src-tauri/src/core/agent/prefix_stability.rsindex 077d76167..f68628c17 100644--- a/src-tauri/src/core/agent/prefix_stability.rs+++ b/src-tauri/src/core/agent/prefix_stability.rs@@ -287,6 +287,7 @@ async fn advertise(project: &Path) -> Vec<Value> {4,false,true,+ &crate::core::agent::host_tools::HostToolSet::new(),).await;// An empty array would make every array comparison below vacuous.diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex b7f503233..585eb14ff 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -1295,6 +1295,18 @@ async fn run_subagent(// above), so it has no registry to share; clearing this keeps it from// inheriting the parent session's by accident.child_args.subagent_bg = None;+ // Host tools are the client's to execute, and a client answers a+ // `tool_request` it can see. A child's events reach stdout wrapped in+ // `Subagent { .. }`, a shape no client is told it may answer, so a child+ // that inherited the set would raise a request nobody could resolve: the+ // strand guard matches only a top-level request, and the turn would park.+ // A child therefore advertises no host tools at all, for the same reason+ // `ask_requests` is cleared above -- no client is attached to a child run.+ #[cfg(feature = "cli")]+ {+ child_args.host_tools = crate::core::agent::host_tools::HostToolSet::new();+ child_args.host_tool_requests = crate::core::agent::host_tools::new_registry();+ }let body = child_body(&resolved, &description, &parent);@@ -3134,6 +3146,8 @@ mod tests {permissions: ToolPermissions::allow_all(),project_root: Some(root.to_path_buf()),permission_requests: Arc::new(tokio::sync::Mutex::new(HashMap::new())),+ host_tools: crate::core::agent::host_tools::HostToolSet::new(),+ host_tool_requests: crate::core::agent::host_tools::new_registry(),ask_requests: None,todo_registry: None,system_prompt_override: None,@@ -4024,6 +4038,26 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A child's events reach stdout wrapped in `Subagent { .. }`, and the+ /// forwarder is a *negative* match: anything not explicitly held back is+ /// forwarded, so a nested `ToolRequest` would be handed to a client that is+ /// told nothing about the wrapper and could not answer it. Nothing here+ /// filters that shape, which is exactly why `run_subagent` clears the+ /// child's host tool set instead: the request is never raised at all.+ #[test]+ fn a_nested_tool_request_would_reach_the_parent_unfiltered() {+ use crate::core::agent::events::StreamEvent;+ assert!(+ forward_to_parent(&StreamEvent::ToolRequest {+ request_id: "host-1".to_string(),+ tool_name: "robot_arm_move".to_string(),+ args: serde_json::json!({}),+ }),+ "the forwarder does not hold back a nested tool_request, so a child \+ must never own host tools in the first place"+ );+ }+#[test]fn create_rejects_plugin_scope() {let root = unique_root("plugin-create");diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 98955b4f6..554d71a84 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1075,6 +1075,7 @@ pub async fn cli_agent_run(resume: Option<ResumeRequest>,format: OutputFormat,input_format: InputFormat,+ host_tools: Option<&str>,) -> Result<(), String> {run_agent_loop(project,@@ -1086,6 +1087,7 @@ pub async fn cli_agent_run(resume,format,input_format,+ host_tools,).await}@@ -1109,6 +1111,9 @@ pub async fn cli_agent_step(None,OutputFormat::Text,InputFormat::Text,+ // `step` is a debugging path with no client on stdin, so there is+ // nothing that could execute a host tool.+ None,).await}@@ -1121,6 +1126,8 @@ fn build_cli_orchestration_args(mcp_servers: crate::core::state::SharedMcpServers,mcp_settings: McpSettings,permission_requests: PermissionRegistry,+ host_tools: crate::core::agent::host_tools::HostToolSet,+ host_tool_requests: crate::core::agent::host_tools::HostToolRegistry,auto_approve: bool,plan: bool,max_parallel_subagents: u32,@@ -1135,6 +1142,8 @@ fn build_cli_orchestration_args(permissions,project_root: Some(project_root),permission_requests,+ host_tools,+ host_tool_requests,ask_requests: None,todo_registry: None,system_prompt_override: None,@@ -1638,6 +1647,13 @@ fn prepare_agent_session(mcp_servers.clone(),mcp_settings,permission_requests.clone(),+ // Host tools are declared per *run*, by a client on stdin, so the+ // session is built without them and the duplex headless path installs+ // the declared set before orchestration starts. The TUI leaves this+ // empty, and `run_subagent` clears it for a child, so neither emits a+ // `tool_request` -- only a run with a client that can answer one does.+ crate::core::agent::host_tools::HostToolSet::new(),+ crate::core::agent::host_tools::new_registry(),flags.auto_approve,flags.plan,max_parallel_subagents,@@ -1834,6 +1850,20 @@ fn short_id(id: &str) -> String {id.chars().take(8).collect()}+/// Read a host's tool declarations from the file `--host-tools` names.+///+/// Every failure is the host's to fix and is reported with the path, since a+/// host that mistyped one is otherwise left guessing which of its tools the run+/// disagreed with.+fn load_host_tools(path: &str) -> Result<crate::core::agent::host_tools::HostToolSet, String> {+ let raw = std::fs::read_to_string(path)+ .map_err(|e| format!("cannot read --host-tools file '{path}': {e}"))?;+ let decls: Vec<crate::core::agent::host_tools::HostToolDecl> = serde_json::from_str(&raw)+ .map_err(|e| format!("--host-tools file '{path}' is not a list of tool declarations: {e}"))?;+ crate::core::agent::host_tools::HostToolSet::declare(decls)+ .map_err(|e| format!("--host-tools file '{path}': {e}"))+}+#[allow(clippy::too_many_arguments)]async fn run_agent_loop(project: &str,@@ -1845,6 +1875,7 @@ async fn run_agent_loop(resume: Option<ResumeRequest>,format: OutputFormat,input_format: InputFormat,+ host_tools: Option<&str>,) -> 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@@ -1853,14 +1884,56 @@ async fn run_agent_loop(// 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();+ // Every refusal below is a setup failure like any other, so it is reported+ // the way `prepare_agent_run`'s is: one `result` record with+ // `error.code: "setup_error"`. Returning early instead would leave a+ // machine consumer an empty stdout and a human string on stderr, which is+ // the one thing this channel promises never to do -- and a mistyped+ // `--host-tools` path is the first failure a host is likely to hit.+ let setup = (|| {+ 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(),+ );+ }+ // Declared before anything is spent: a malformed or unacceptable tool+ // set is the host's own mistake, and finding out at the first call --+ // mid-task, after paid requests -- is worse than refusing to start.+ match host_tools {+ Some(path) => {+ if !input_format.is_stream_json() {+ return Err(+ "--host-tools requires --input-format stream-json (a host tool call is \+ answered with a tool_result message on stdin)"+ .to_string(),+ );+ }+ load_host_tools(path)+ }+ None => Ok(crate::core::agent::host_tools::HostToolSet::new()),+ }+ })();+ let host_tools = match setup {+ Ok(host_tools) => host_tools,+ Err(e) => {+ if format.is_machine() {+ print_report(+ format,+ RunReport::setup_failure(&e).finish(+ None,+ None,+ "",+ started.elapsed().as_millis(),+ None,+ ),+ );+ }+ return Err(e);+ }+ };let prepared = prepare_agent_run(project,task,@@ -1873,7 +1946,7 @@ async fn run_agent_loop(// A setup failure never reaches the event stream, so a JSON consumer would// otherwise get an empty stdout and have to parse the human error off stderr.let PreparedRun {- args,+ mut args,body,provider,permission_requests,@@ -1897,6 +1970,10 @@ async fn run_agent_loop(return Err(e);}};+ // Installed after the session is built, since host tools are declared per+ // run rather than per project: the same session config serves a run with+ // them and one without.+ args.host_tools = host_tools;// Block until active MCP servers connect, so tools (collected once per run)// are present on the first turn.@@ -1946,9 +2023,15 @@ async fn run_agent_loop(.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)+ spawn_input_reader(+ Arc::clone(input),+ Arc::clone(&permission_requests),+ Arc::clone(&args.host_tool_requests),+ format,+ )});let client = input.clone();+ let host_tool_requests = Arc::clone(&args.host_tool_requests);let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();// The report is folded in both formats from the same stream the printer@@ -1969,6 +2052,16 @@ async fn run_agent_loop(// 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());+ // Only the client can answer a host tool call. If it has already+ // left, the call is failed here: `strand_all` fired when stdin+ // closed, so nothing else will ever release this one and the turn+ // would park forever.+ if let StreamEvent::ToolRequest { request_id, .. } = &ev {+ if !duplex {+ crate::core::agent::host_tools::strand(&host_tool_requests, request_id).await;+ continue;+ }+ }match format {OutputFormat::Text => print_event(ev, &permission_requests, duplex).await,OutputFormat::Json => {@@ -2074,7 +2167,7 @@ async fn init_record(model: &str,input_format: InputFormat,) -> Init {- let tools = crate::core::agent::r#loop::context_advertised_tools(+ let tools: Vec<String> = crate::core::agent::r#loop::context_advertised_tools(&args.mcp_servers,&args.mcp_settings,&args.permissions,@@ -2084,11 +2177,29 @@ async fn init_record(args.max_parallel_subagents,args.ask_requests.is_some(),args.todo_registry.is_some(),+ &args.host_tools,).await.iter().filter_map(tool_name).collect();+ // Only the host tools' schemas are echoed, not every advertised tool's: the+ // host is comparing these against what it sent, and a built-in's schema is+ // this process's own business.+ //+ // Filtered to what `tools` actually advertises rather than to everything+ // declared. A deny list, an allowlist or Plan mode can withhold a host tool,+ // and a host that saw its schema echoed anyway would conclude the tool was+ // live and wait for a call that is never coming. Echoing the advertised set+ // lets it detect the suppression instead.+ let tool_specs = args+ .host_tools+ .schemas()+ .into_iter()+ .filter(|spec| {+ tool_name(spec).is_some_and(|name| tools.iter().any(|t| t == &name))+ })+ .collect();// The project root the run's tools are confined to, as the run itself sees// it. A caller that built these args without one gets `null`: any path// substituted here would claim a confinement the run does not have.@@ -2114,6 +2225,7 @@ async fn init_record(model,cwd,tools,+ tool_specs,input_kinds,input_content_parts,)@@ -2178,14 +2290,21 @@ enum InputFlow {Stop,}+/// The registries a client line can resolve against.+struct InputTargets<'a> {+ permissions: &'a PermissionRegistry,+ host_tools: &'a crate::core::agent::host_tools::HostToolRegistry,+}+/// 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,+ targets: &InputTargets<'_>,) -> Result<InputFlow, String> {+ let registry = targets.permissions;match parse_input_line(line)? {InputMessage::User(text) => {input.queue_user(text);@@ -2213,6 +2332,15 @@ async fn apply_input_line(let _ = sender.send(decision);Ok(InputFlow::Decided(request_id, decision))}+ InputMessage::ToolResult { request_id, result } => {+ // Same single-use rule as a permission decision, and the same+ // reason: the run has already fed this answer to the model, so a+ // second one cannot be applied and must be reported rather than+ // silently dropped.+ crate::core::agent::host_tools::respond(targets.host_tools, &request_id, Ok(result))+ .await?;+ Ok(InputFlow::Continue)+ }}}@@ -2300,15 +2428,21 @@ fn read_bounded_line<R: std::io::BufRead>(////// 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`].+/// only thing that can answer a permission request or run a host tool, though,+/// so the exit is latched and anything already waiting is released -- see+/// [`strand_pending_permissions`] and+/// [`crate::core::agent::host_tools::strand_all`].async fn read_input_lines(mut lines: mpsc::UnboundedReceiver<ClientLine>,input: Arc<StreamInput>,registry: PermissionRegistry,+ host_tools: crate::core::agent::host_tools::HostToolRegistry,format: OutputFormat,) {+ let targets = InputTargets {+ permissions: ®istry,+ host_tools: &host_tools,+ };while let Some(line) = lines.recv().await {if line.oversized {report_input_error(@@ -2322,7 +2456,7 @@ async fn read_input_lines(if line.trim().is_empty() {continue;}- match apply_input_line(&line, &input, ®istry).await {+ match apply_input_line(&line, &input, &targets).await {Ok(InputFlow::Continue) => {}Ok(InputFlow::Decided(request_id, decision)) => {if format.is_stream_json() {@@ -2337,6 +2471,9 @@ async fn read_input_lines(// otherwise be recorded as the client's to answer and find no reader.input.mark_client_gone();strand_pending_permissions(®istry, format).await;+ // A host tool call cannot be answered by anyone else, so a parked turn is+ // released with a typed failure rather than waiting on a dead pipe.+ crate::core::agent::host_tools::strand_all(&host_tools).await;}/// Name the follow-ups the run ended before reaching. Queued turns are joined@@ -2377,9 +2514,16 @@ async fn strand_pending_permissions(registry: &PermissionRegistry, format: Outpufn spawn_input_reader(input: Arc<StreamInput>,registry: PermissionRegistry,+ host_tools: crate::core::agent::host_tools::HostToolRegistry,format: OutputFormat,) -> tokio::task::JoinHandle<()> {- tokio::spawn(read_input_lines(stdin_lines(), input, registry, format))+ tokio::spawn(read_input_lines(+ stdin_lines(),+ input,+ registry,+ host_tools,+ format,+ ))}/// Tell the client its line was rejected, on whichever stream it is reading.@@ -2640,6 +2784,18 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry, duplex: boolet _ = sender.send(decision);}}+ // Only a host process can answer this, and only over the duplex+ // channel; a text-format run cannot declare host tools at all (the+ // flag requires stream-json both ways), so this is diagnostics only.+ StreamEvent::ToolRequest {+ request_id,+ tool_name,+ ..+ } => {+ eprintln!(+ "\x1b[33m[host tool] '{tool_name}' - awaiting '{request_id}' on stdin\x1b[0m"+ );+ }}}@@ -2712,6 +2868,7 @@ mod tests {lines,Arc::clone(&input),Arc::clone(®istry),+ crate::core::agent::host_tools::new_registry(),OutputFormat::Json,).await;@@ -2740,19 +2897,58 @@ mod tests {registry.lock().await.insert("perm-1".to_string(), tx);let line = r#"{"type":"permission","request_id":"perm-1","decision":"deny"}"#;+ let host_tools = crate::core::agent::host_tools::new_registry();+ let targets = InputTargets {+ permissions: ®istry,+ host_tools: &host_tools,+ };assert_eq!(- apply_input_line(line, &input, ®istry).await,+ apply_input_line(line, &input, &targets).await,Ok(InputFlow::Decided("perm-1".to_string(),PermissionDecision::Deny)));- let err = apply_input_line(line, &input, ®istry)+ let err = apply_input_line(line, &input, &targets).await.expect_err("nothing is pending any more");assert!(err.contains("no permission request 'perm-1'"), "{err}");}+ /// The same single-use rule for a host tool answer, and the same reason:+ /// the first result has already been fed to the model.+ #[tokio::test]+ async fn a_second_tool_result_for_one_request_is_rejected() {+ let input = StreamInput::default();+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let host_tools = crate::core::agent::host_tools::new_registry();+ // The id comes from the registry: the counter is process-wide, so a+ // literal would depend on which tests ran first.+ let (id, answer) = crate::core::agent::host_tools::register(&host_tools).await;+ let targets = InputTargets {+ permissions: ®istry,+ host_tools: &host_tools,+ };+ let line = format!(r#"{{"type":"tool_result","request_id":"{id}","content":"moved"}}"#);+ let line = line.as_str();++ assert_eq!(+ apply_input_line(line, &input, &targets).await,+ Ok(InputFlow::Continue)+ );+ assert_eq!(+ answer.await.expect("the run's tool wait is answered"),+ Ok(crate::core::agent::host_tools::HostToolResult {+ content: "moved".to_string(),+ is_error: false,+ })+ );+ let err = apply_input_line(line, &input, &targets)+ .await+ .expect_err("nothing is pending any more");+ assert!(err.contains(&format!("no host tool request '{id}'")), "{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`.@@ -2773,6 +2969,7 @@ mod tests {lines,Arc::clone(&input),Arc::clone(®istry),+ crate::core::agent::host_tools::new_registry(),OutputFormat::StreamJson,).await;@@ -2788,14 +2985,58 @@ mod tests {);}- /// 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.+ /// The same wedge for a host tool, where it is sharper: only the client can+ /// answer a `tool_request`, so a pipe that closes mid-call would park the+ /// turn forever rather than merely losing a decision default.#[tokio::test]- async fn a_request_raised_after_the_client_left_is_not_left_to_the_client() {+ async fn a_pending_host_tool_call_is_released_when_the_client_leaves() {+ let input = Arc::new(StreamInput::default());+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let host_tools = crate::core::agent::host_tools::new_registry();+ let (_id, answer) = crate::core::agent::host_tools::register(&host_tools).await;++ let (lines_tx, lines) = mpsc::unbounded_channel::<ClientLine>();+ drop(lines_tx);+ read_input_lines(+ lines,+ Arc::clone(&input),+ Arc::clone(®istry),+ Arc::clone(&host_tools),+ OutputFormat::StreamJson,+ )+ .await;++ assert_eq!(+ answer.await.expect("the wait is settled, not dropped"),+ Err(crate::core::agent::host_tools::HostToolError::ClientGone)+ );+ assert!(host_tools.lock().await.is_empty());+ }++ /// The other half of the same wedge, and the sharper half: a request raised+ /// *after* the pipe closed. `strand_all` has already run by then, so unless+ /// the printer fails this call itself the turn parks on a reply no one is+ /// left to send. Asserts the release, not merely that the latch flipped.+ #[tokio::test]+ async fn a_request_raised_after_the_client_left_is_failed_not_parked() {let input = StreamInput::default();- assert!(!input.client_gone());+ let host_tools = crate::core::agent::host_tools::new_registry();++ // The client leaves, and the reader drains what was pending.input.mark_client_gone();+ crate::core::agent::host_tools::strand_all(&host_tools).await;++ // Only now does the model call a host tool.+ let (request_id, answer) =+ crate::core::agent::host_tools::register(&host_tools).await;assert!(input.client_gone());+ crate::core::agent::host_tools::strand(&host_tools, &request_id).await;++ assert_eq!(+ answer.await.expect("the wait is settled, not dropped"),+ Err(crate::core::agent::host_tools::HostToolError::ClientGone)+ );+ assert!(host_tools.lock().await.is_empty());}/// `--input-format stream-json` with any other output format leaves the@@ -2813,6 +3054,7 @@ mod tests {None,format,InputFormat::StreamJson,+ None,).await.expect_err("the pairing is required");@@ -2843,7 +3085,14 @@ mod tests {}).expect("reader is alive");drop(lines_tx);- read_input_lines(lines, Arc::clone(&input), registry, OutputFormat::Json).await;+ read_input_lines(+ lines,+ Arc::clone(&input),+ registry,+ crate::core::agent::host_tools::new_registry(),+ OutputFormat::Json,+ )+ .await;let queued = input.take_queued();assert_eq!(queued.len(), 1, "the follow-up is queued as one turn");diff --git a/src-tauri/src/core/cli/protocol_schema.rs b/src-tauri/src/core/cli/protocol_schema.rsindex b1ff079b6..e18e87560 100644--- a/src-tauri/src/core/cli/protocol_schema.rs+++ b/src-tauri/src/core/cli/protocol_schema.rs@@ -241,6 +241,7 @@ mod tests {None,Vec::new(),Vec::new(),+ Vec::new(),None,)).unwrap(),diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rsindex dbb43ac4c..3a48adcff 100644--- a/src-tauri/src/core/cli/run_report.rs+++ b/src-tauri/src/core/cli/run_report.rs@@ -15,7 +15,7 @@//! `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`. Four tags are minted by+//! `turn_usage`, `done`, `error`, `permission_request`, `tool_request`. Four tags are minted by//! the CLI rather than by the loop: `init`, `permission_decision`, `result` and//! `input_error`. `init` is the handshake a client reads before any other record//! (see [`Init`]); `permission_decision` reports how this CLI answered a gated@@ -279,6 +279,17 @@ pub(crate) struct Init {/// 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>,+ /// The full schemas of the host tools this run advertises. A host compares+ /// these against what it declared, which is the only way to know its+ /// constraints survived rather than trusting that they did; the names in+ /// `tools` alone cannot answer that.+ ///+ /// This is the advertised subset, not everything declared: a deny list, an+ /// allowlist or Plan mode can withhold a host tool, and its absence here is+ /// how a host learns that happened. Omitted entirely when the run+ /// advertises no host tools, so an ordinary run's handshake is unchanged.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ tool_specs: Vec<serde_json::Value>,/// 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.@@ -335,6 +346,7 @@ impl Init {model: &str,cwd: Option<String>,tools: Vec<String>,+ tool_specs: Vec<serde_json::Value>,input_kinds: Vec<&'static str>,input_content_parts: Option<InputContentParts>,) -> Self {@@ -345,6 +357,7 @@ impl Init {model: model.to_string(),cwd,tools,+ tool_specs,input_kinds,input_content_parts,}@@ -556,6 +569,7 @@ mod tests {Some("/tmp".to_string()),Vec::new(),Vec::new(),+ Vec::new(),None,)).unwrap(),@@ -620,6 +634,7 @@ mod tests {"stub-model",Some("/tmp/project".to_string()),vec!["read".to_string(), "write".to_string()],+ Vec::new(),vec!["user", "abort", "permission"],Some(InputContentParts::current()),))@@ -650,6 +665,36 @@ mod tests {);}+ /// R5: a host compares the schemas it gets back against the ones it sent,+ /// so they travel in the handshake verbatim -- constraints a normalizer+ /// would strip included.+ #[test]+ fn init_echoes_the_host_tool_schemas_it_installed() {+ let spec = serde_json::json!({+ "type": "function",+ "function": {+ "name": "host__observe",+ "description": "look",+ "parameters": {+ "type": "object",+ "properties": { "n": { "type": "array", "minItems": 2 } },+ "additionalProperties": false+ }+ }+ });+ let out = serde_json::to_value(Init::new(+ "id",+ "m",+ Some("/tmp".to_string()),+ vec!["host__observe".to_string()],+ vec![spec.clone()],+ vec!["user", "tool_result"],+ None,+ ))+ .unwrap();+ assert_eq!(out["tool_specs"], serde_json::json!([spec]));+ }+/// 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.@@ -661,6 +706,7 @@ mod tests {Some("/tmp".to_string()),Vec::new(),Vec::new(),+ Vec::new(),None,)).unwrap();@@ -682,10 +728,15 @@ mod tests {None,Vec::new(),Vec::new(),+ Vec::new(),None,)).unwrap();assert!(out["cwd"].is_null(), "{out}");+ assert!(+ out.get("tool_specs").is_none(),+ "a run with no host tools leaves the handshake as it was: {out}"+ );}/// The envelope carries the same version, so a `--output-format json`diff --git a/src-tauri/src/core/cli/stream_input.rs b/src-tauri/src/core/cli/stream_input.rsindex 009abea6b..d392134af 100644--- a/src-tauri/src/core/cli/stream_input.rs+++ b/src-tauri/src/core/cli/stream_input.rs@@ -8,10 +8,13 @@//! 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:+//! Four kinds, matching the things a caller cannot otherwise say://! `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).+//! via the orchestration loop's existing steering handshake), `abort`,+//! `permission` (a decision keyed to a `permission_request` already on stdout),+//! and `tool_result` (the answer to a `tool_request`, which is how a host+//! executes a tool this process cannot: see+//! [`crate::core::agent::host_tools`]).//! [`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@@ -24,6 +27,7 @@//! passed through verbatim; the caps below are what a line is measured against//! first, because an unbounded channel is a denial of service on the run.+use crate::core::agent::host_tools::HostToolResult;use std::collections::VecDeque;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Mutex;@@ -70,7 +74,7 @@ impl InputFormat {/// 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"];+pub(crate) const INPUT_KINDS: [&str; 4] = ["user", "abort", "permission", "tool_result"];/// One well-formed line from the client.#[derive(Debug, PartialEq, Eq)]@@ -87,9 +91,15 @@ pub(crate) enum InputMessage {request_id: String,decision: PermissionDecision,},+ /// The answer to a `tool_request` this run emitted: the host ran the tool+ /// and this is what the model should see.+ ToolResult {+ request_id: String,+ result: HostToolResult,+ },}-/// One input line, as the wire shape: the three [`INPUT_KINDS`], with the fields+/// One input line, as the wire shape: the [`INPUT_KINDS`], with the fields/// each carries. The wire shape is a serde type rather than a hand-rolled walk/// over a `Value` so the protocol schema can be derived from it -- `jan cli/// agent schema` publishes this shape, and a hand-written copy of it would be@@ -118,6 +128,18 @@ pub(crate) enum InputLine {request_id: String,decision: InputDecision,},+ /// The answer to a `tool_request` this run emitted: the host executed the+ /// tool and this is its result, which becomes the model's tool message.+ ///+ /// `content` is required even for a failure. A tool message with nothing in+ /// it tells the model only that something happened, which is worse than a+ /// short error.+ ToolResult {+ request_id: String,+ content: String,+ #[serde(default)]+ is_error: bool,+ },}/// The decisions a client may answer a `permission_request` with: the wire@@ -177,6 +199,14 @@ pub(crate) fn parse_input_line(line: &str) -> Result<InputMessage, String> {request_id,decision: decision.into(),}),+ InputLine::ToolResult {+ request_id,+ content,+ is_error,+ } => Ok(InputMessage::ToolResult {+ request_id,+ result: HostToolResult { content, is_error },+ }),}}@@ -363,7 +393,7 @@ mod tests {use super::*;#[test]- fn the_three_message_kinds_parse() {+ fn the_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())@@ -382,6 +412,38 @@ mod tests {decision: PermissionDecision::AllowOnce,});+ assert_eq!(+ parse_input_line(+ r#"{"type":"tool_result","request_id":"host-1","content":"3 joints moved"}"#+ )+ .unwrap(),+ InputMessage::ToolResult {+ request_id: "host-1".to_string(),+ result: HostToolResult {+ content: "3 joints moved".to_string(),+ is_error: false,+ },+ }+ );+ }++ /// A host tool that failed is still an answer: the model is told what went+ /// wrong and can choose another route, rather than the turn ending.+ #[test]+ fn a_failed_tool_result_is_carried_as_one() {+ assert_eq!(+ parse_input_line(+ r#"{"type":"tool_result","request_id":"host-2","content":"arm is estopped","is_error":true}"#+ )+ .unwrap(),+ InputMessage::ToolResult {+ request_id: "host-2".to_string(),+ result: HostToolResult {+ content: "arm is estopped".to_string(),+ is_error: true,+ },+ }+ );}/// The advertised kinds and the accepted ones are one list. A kind the@@ -400,6 +462,9 @@ mod tests {"user" => r#"{"type":"user","text":"hello"}"#,"abort" => r#"{"type":"abort"}"#,"permission" => r#"{"type":"permission","request_id":"p1","decision":"deny"}"#,+ "tool_result" => {+ r#"{"type":"tool_result","request_id":"h1","content":"done"}"#+ }other => panic!("'{other}' is advertised but has no sample line here"),};assert!(@@ -454,6 +519,18 @@ mod tests {r#"{"type":"permission","request_id":"p","decision":"maybe"}"#,"unknown variant `maybe`, expected one of `allow_once`, `allow_always`, `deny`",),+ (+ r#"{"type":"tool_result","content":"x"}"#,+ "missing field `request_id`",+ ),+ (+ r#"{"type":"tool_result","request_id":"h1"}"#,+ "missing field `content`",+ ),+ (+ r#"{"type":"tool_result","request_id":"h1","content":"x","is_error":"yes"}"#,+ "invalid type: string \"yes\", expected a boolean",+ ),] {let err = parse_input_line(line).expect_err(line);assert!(err.contains(marker), "{line}: {err} lacks {marker}");diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex e145cde05..9acb61b9e 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -5182,6 +5182,7 @@ async fn compute_context_report(snapshot: ContextSnapshot) -> ContextReport {args.max_parallel_subagents,args.ask_requests.is_some(),args.todo_registry.is_some(),+ &args.host_tools,).await.iter()@@ -5544,6 +5545,11 @@ impl App {));self.publish_agent_status();}+ // Host tools belong to a headless run driven by a host process.+ // The TUI is that host's opposite number -- there is no peer on+ // stdin to execute a callback -- so it never declares them and+ // cannot receive this.+ StreamEvent::ToolRequest { .. } => {}// The loop auto-answered a timed-out ask; drop its now-dead prompt.// A user answer clears the queue in `resolve_front_ask` instead, so// this only fires for the timeout path.@@ -25251,6 +25257,8 @@ mod tests {permission_requests: std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new(),)),+ host_tools: crate::core::agent::host_tools::HostToolSet::new(),+ host_tool_requests: crate::core::agent::host_tools::new_registry(),ask_requests: None,todo_registry: None,system_prompt_override: None,