Craft Anything: understand how any software works, and craft your own.
Rust
Offer Grok Build as a coding agent over ACP (#1029)
Harrison Smith9f4c3c209b3c
diff --git a/README.md b/README.mdindex 290d979a..3573f6e8 100644--- a/README.md+++ b/README.md@@ -159,9 +159,11 @@ Anything runs your own, unmodified `claude` program, which uses your own sign-innever sees or handles your account. Your use of it falls under your own agreement withAnthropic. See [docs/claude-code.md](docs/claude-code.md) for how and why. A Codex adapterexists but hasn't been verified on a real install yet. **GitHub Copilot** can use your installed-Copilot CLI through ACP: sign in separately with `copilot login`. Other agents that speak ACP (Gemini CLI,+Copilot CLI through ACP: sign in separately with `copilot login`. **Grok Build** can use your+installed `grok` program through ACP (`grok agent stdio`): sign in separately with `grok login`.+See [docs/grok.md](docs/grok.md). Other agents that speak ACP (Gemini CLI,Qwen Code, opencode, goose, Hermes, Maki) can be switched to it per backend; of those, only Maki has-been run live. Anthropic, OpenAI, OpenRouter and local+been run live. Anthropic, OpenAI, OpenRouter, xAI (Grok, when `XAI_API_KEY` is set) and localOpenAI-compatible servers are available for questions and analysis (Settings → AI).## Built for agentsdiff --git a/crates/ai/src/cli_agents/acp.rs b/crates/ai/src/cli_agents/acp.rsindex cc4a3cd7..0185300a 100644--- a/crates/ai/src/cli_agents/acp.rs+++ b/crates/ai/src/cli_agents/acp.rs@@ -31,11 +31,13 @@ pub const ACP_AGENTS: &[(&str, &[&str])] = &[("hermes", &["acp"]),("maki", &["acp"]),("copilot", &["--acp", "--stdio"]),+ // Flags that belong to this mode (`--model`, `--no-leader`) go between `agent` and `stdio`.+ ("grok", &["agent"]),];/// Agents whose ACP mode takes the backend's model (`cli_model`), and the flag after the ACP/// arguments that picks it. Others keep the model they're set to.-pub const ACP_MODEL_FLAGS: &[(&str, &str)] = &[("maki", "-m")];+pub const ACP_MODEL_FLAGS: &[(&str, &str)] = &[("maki", "-m"), ("grok", "--model")];/// The arguments after `agent`'s ACP ones that pick `model`; none when its ACP mode isn't known/// to take one.@@ -116,6 +118,9 @@ enum Pending {Initialize,NewSession,LoadSession,+ /// `session/set_config_option`. The session is not ready until these finish: model discovery+ /// waits on `ready`, and some agents replace the CLI's model flag when the session opens.+ SetConfig,Prompt,}@@ -153,6 +158,13 @@ pub struct AcpCore {models: Vec<String>,current_model: String,config_options: Vec<Value>,+ /// `(configId, value)` applied in order after the session opens, before it is ready.+ config_queue: VecDeque<(String, String)>,+ /// A loaded session already has history. Set when the session response arrives, and copied+ /// onto [`session_has_history`](Self::session_has_history) once the config queue is done.+ opened_with_history: bool,+ /// The adapter asked for `"type": "stdio"` on our MCP server. Off for every other agent.+ typed_mcp: bool,}impl AcpCore {@@ -178,6 +190,9 @@ impl AcpCore {models: Vec::new(),current_model: String::new(),config_options: Vec::new(),+ config_queue: VecDeque::new(),+ opened_with_history: false,+ typed_mcp: false,}}@@ -236,7 +251,45 @@ impl AcpCore {}fn mcp_servers(&self) -> Value {- if self.question { json!([]) } else { json!([{"name": super::MCP_NAME, "command": self.mcp.command, "args": self.mcp.args, "env": []}]) }+ // Questions attach no server. `"type": "stdio"` is only added for an adapter that+ // requires it (Grok). Other agents keep the payload their sessions already accept.+ if self.question {+ return json!([]);+ }+ let mut server = json!({"name": super::MCP_NAME, "command": self.mcp.command, "args": self.mcp.args, "env": []});+ if self.typed_mcp {+ server["type"] = json!("stdio");+ }+ json!([server])+ }++ /// The current string value of a session config option, when the agent reports one.+ fn config_current(options: &[Value], id: &str) -> Option<String> {+ let option = options.iter().find(|option| option.get("id").and_then(Value::as_str) == Some(id))?;+ match option.get("currentValue") {+ Some(Value::String(value)) => Some(value.clone()),+ Some(value) => value.get("value").and_then(Value::as_str).map(str::to_string),+ None => None,+ }+ }++ /// Send the next config override that the session does not already have, then mark it ready.+ /// A value is a JSON string: Grok rejects a nested `{"value": ...}` wrapper.+ fn advance_config(&mut self) -> Vec<Out> {+ while let Some((id, value)) = self.config_queue.front().cloned() {+ if Self::config_current(&self.config_options, &id).as_deref() == Some(value.as_str()) {+ self.config_queue.pop_front();+ continue;+ }+ let Some(sid) = self.session.clone() else {+ return self.fail(format!("{} started no session", self.agent_name), None);+ };+ let params = json!({"sessionId": sid, "configId": id, "value": value});+ return vec![self.request("session/set_config_option", params, Pending::SetConfig)];+ }+ self.ready = true;+ self.session_has_history = self.opened_with_history;+ self.flush()}/// One line from the agent.@@ -281,9 +334,15 @@ impl AcpCore {Some(-32602..=-32600) => FailureKind::Configuration,_ => FailureKind::Unknown,}));- let fix = matches!(kind, Pending::Initialize | Pending::NewSession).then(|| {- self.sign_in_fix.clone().unwrap_or_else(|| format!("Check that {} is installed and signed in: run it once in a terminal.", self.agent_name))- });+ let fix = match kind {+ Pending::Initialize | Pending::NewSession => Some(+ self.sign_in_fix+ .clone()+ .unwrap_or_else(|| format!("Check that {} is installed and signed in: run it once in a terminal.", self.agent_name)),+ ),+ Pending::SetConfig => Some("Choose a model and thinking depth this agent lists, then try again.".into()),+ Pending::LoadSession | Pending::Prompt => None,+ };return self.fail(format!("{}: {text}", self.agent_name), fix);}let result = msg.get("result").unwrap_or(&Value::Null);@@ -321,9 +380,21 @@ impl AcpCore {if self.session.is_none() {return self.fail(format!("{} started no session", self.agent_name), None);}- self.ready = true;- self.session_has_history = kind == Pending::LoadSession;- self.flush()+ // Ready waits until the queued overrides are applied. Grok's `--model` flag does+ // not survive `session/new`; the saved default comes back and has to be set here.+ self.opened_with_history = kind == Pending::LoadSession;+ self.advance_config()+ }+ Pending::SetConfig => {+ if let Some(options) = result.get("configOptions").and_then(Value::as_array) {+ self.config_options = options.clone();+ }+ if let Some(model) = Self::config_current(&self.config_options, "model").filter(|model| !model.is_empty()) {+ self.current_model = model;+ }+ // One attempt. A response that does not echo the new value is not sent again.+ self.config_queue.pop_front();+ self.advance_config()}Pending::Prompt => {let mut out = Vec::new();@@ -528,6 +599,10 @@ pub struct AcpConversation {question: bool,/// Report invalid backend settings through the conversation before starting a child process.validation_error: Option<craft_anything_evidence::ToolError>,+ /// An access mode this agent cannot hold. Cleared for model-list discovery, which sends no prompt.+ access_error: Option<craft_anything_evidence::ToolError>,+ /// Copied onto the core when the process starts, and applied before the session is ready.+ session_config: Vec<(String, String)>,}impl AcpConversation {@@ -546,6 +621,9 @@ impl AcpConversation {pub(crate) fn model_metadata_with_stop(mut self, timeout: Duration, stop: &Stop) -> Result<ModelMetadata, craft_anything_evidence::ToolError> {stop.check()?;+ // No prompt is sent. The question-shaped session only keeps the tool server off, so a+ // refusal of questions and Clean room does not apply to reading the model list.+ self.access_error = None;self.spawn()?;self.busy.store(true, Ordering::SeqCst);let started = Instant::now();@@ -587,6 +665,12 @@ impl AcpConversation {self}+ /// Keep an access-mode refusal until the conversation starts. Model-list discovery clears it.+ pub fn with_access_limit(mut self, result: Result<(), craft_anything_evidence::ToolError>) -> Self {+ self.access_error = result.err();+ self+ }+/// A read-only question: attach no MCP server and refuse permission requests. The caller/// must also choose a fresh session and restrictive agent flags; this switch alone doesn't/// prevent native tools from running without a permission request.@@ -614,6 +698,12 @@ impl AcpConversation {self}+ /// Config options applied with `session/set_config_option` after `session/new` or `session/load`.+ pub fn with_session_config(mut self, config: Vec<(String, String)>) -> Self {+ self.session_config = config;+ self+ }+/// A builder run: the agent's permission requests are decided by `approver` (the approval/// policy), not asked in the chat.pub fn with_approver(mut self, approver: Approver) -> Self {@@ -644,6 +734,8 @@ impl AcpConversation {failure: None,question: false,validation_error: None,+ access_error: None,+ session_config: Vec::new(),}}@@ -653,14 +745,16 @@ impl AcpConversation {/// Start the agent and send `initialize`.fn spawn(&mut self) -> Result<(), craft_anything_evidence::ToolError> {- if let Some(error) = &self.validation_error {- return Err(error.clone());+ if let Some(error) = self.validation_error.clone().or_else(|| self.access_error.clone()) {+ return Err(error);}let name = display_for(&self.agent);let resume = self.lock().as_ref().and_then(|s| s.core.session_id()).or_else(|| self.resume.clone());let mut core = AcpCore::new(&self.backend, &name, self.cwd.clone(), self.mcp.clone(), resume);core.question = self.question;core.sign_in_fix = self.adapter.sign_in_fix();+ core.typed_mcp = self.adapter.acp_mcp_stdio_type();+ core.config_queue = VecDeque::from(self.session_config.clone());if self.approver.is_some() {core = core.deciding();}@@ -861,12 +955,14 @@ mod tests {#[test]fn model_metadata_deadlines_name_the_current_agent() {- for (agent, name) in [("gemini-cli", "Gemini CLI"), ("copilot", "GitHub Copilot")] {+ for (agent, name) in [("gemini-cli", "Gemini CLI"), ("copilot", "GitHub Copilot"), ("grok", "Grok Build")] {let mcp = McpCommand { command: "not-started".into(), args: Vec::new(), notes: None };let conversation = AcpConversation::new("Test", agent, "not-started".into(), Vec::new(), PathBuf::new(), mcp, None);let error = conversation.model_metadata_timeout();assert_eq!(error.message, format!("{name} did not list its models before the deadline."));- assert_eq!(error.remediation.unwrap().contains("copilot login"), agent == "copilot");+ let fix = error.remediation.unwrap();+ assert_eq!(fix.contains("copilot login"), agent == "copilot");+ assert_eq!(fix.contains("grok login"), agent == "grok");}}@@ -907,6 +1003,7 @@ mod tests {assert_eq!(new[0]["method"], "session/new");assert_eq!(new[0]["params"]["cwd"], "/w/project");assert_eq!(new[0]["params"]["mcpServers"][0]["name"], "craft-anything");+ assert!(new[0]["params"]["mcpServers"][0].get("type").is_none(), "only an adapter that asks sends type");assert_eq!(new[0]["params"]["mcpServers"][0]["env"], json!([]));let prompt = sent(&c.line(r#"{"jsonrpc":"2.0","id":2,"result":{"sessionId":"s-1"}}"#));assert_eq!(prompt[0]["method"], "session/prompt");@@ -1193,6 +1290,168 @@ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$prompt};let Some(c) = super::super::acp_for(&super::super::CliSpec::new(config, options, false, None)) else { panic!("Maki speaks ACP") };assert_eq!((c.program.as_str(), c.args.as_slice()), ("maki", &["--no-plugins", "acp", "-m", "anthropic/claude-sonnet-4-6"].map(String::from)[..]));+ assert!(!c.adapter.acp_mcp_stdio_type());+ }++ /// Grok's server enum needs `"type": "stdio"`. A session for any other agent leaves it off,+ /// and a question still attaches no server.+ #[test]+ fn only_grok_sends_a_typed_stdio_server() {+ let mut plain = core(None);+ plain.start();+ let untyped = sent(&plain.line(r#"{"jsonrpc":"2.0","id":1,"result":{"agentCapabilities":{"loadSession":true}}}"#));+ assert_eq!(untyped[0]["method"], "session/new");+ assert!(untyped[0]["params"]["mcpServers"][0].get("type").is_none());++ let mut grok = core(None);+ grok.typed_mcp = true;+ grok.start();+ let typed = sent(&grok.line(r#"{"jsonrpc":"2.0","id":1,"result":{"agentCapabilities":{"loadSession":true}}}"#));+ assert_eq!(typed[0]["params"]["mcpServers"][0]["type"], "stdio");+ assert_eq!(typed[0]["params"]["mcpServers"][0]["name"], "craft-anything");++ let mut question = core(None);+ question.question = true;+ question.typed_mcp = true;+ question.start();+ let asked = sent(&question.line(r#"{"jsonrpc":"2.0","id":1,"result":{}}"#));+ assert_eq!(asked[0]["params"]["mcpServers"], json!([]));+ }++ /// `grok agent [flags] stdio`: the model flag and `--no-leader` sit between `agent` and `stdio`.+ #[test]+ fn a_grok_backend_runs_agent_then_its_flags_then_stdio() {+ let options = crate::BackendOptions { cli_model: Some("grok-4.6".into()), cli_thinking: Some(crate::Effort::Low), ..Default::default() };+ let Some(c) = super::super::acp_for(&super::super::CliSpec::new(grok_config(), options, false, None)) else { panic!("Grok speaks ACP") };+ assert_eq!(+ (c.program.as_str(), c.args.as_slice()),+ ("grok", &["agent", "--model", "grok-4.6", "--no-leader", "--reasoning-effort", "low", "stdio"].map(String::from)[..])+ );+ assert_eq!(c.session_config, [("model".into(), "grok-4.6".into()), ("reasoning_effort".into(), "low".into())]);+ assert!(!c.args.iter().any(|arg| arg.contains("always-approve") || arg.contains("yolo")));++ let quiet = crate::BackendOptions::default();+ let Some(plain) = super::super::acp_for(&super::super::CliSpec::new(grok_config(), quiet.clone(), false, None)) else { panic!("Grok speaks ACP") };+ assert_eq!(plain.args, ["agent", "--no-leader", "stdio"]);+ assert!(plain.session_config.is_empty());+ assert!(plain.adapter.acp_mcp_stdio_type());+ // A chat that is not deep is Clean room. Grok cannot hold that, so the run is refused+ // before the process starts. The argv is still the one a deep build uses.+ assert!(plain.access_error.as_ref().is_some_and(|error| error.message.contains("Clean room")));++ let mut question = super::super::CliSpec::new(+ grok_config(),+ crate::BackendOptions { cli_model: Some("grok-4.5".into()), effort: Some(crate::Effort::Medium), ..Default::default() },+ false,+ None,+ );+ question.question = true;+ let Some(asked) = super::super::acp_for(&question) else { panic!("Grok answers questions") };+ assert_eq!(asked.args, ["agent", "--model", "grok-4.5", "--no-leader", "--reasoning-effort", "medium", "stdio"]);+ assert!(asked.question);+ assert!(asked.access_error.as_ref().is_some_and(|error| error.message.contains("question")));+ assert_eq!(asked.session_config, [("model".into(), "grok-4.5".into()), ("reasoning_effort".into(), "medium".into())]);++ // Deep chat is analysis only. Grok can still edit when it never asks, so that run is refused too.+ let mut chat = super::super::CliSpec::new(grok_config(), crate::BackendOptions::default(), false, None);+ chat.deep = true;+ let Some(analyse) = super::super::acp_for(&chat) else { panic!("Grok speaks ACP") };+ assert!(analyse.access_error.as_ref().is_some_and(|error| error.message.contains("deep chat")));+ assert_eq!(analyse.args, ["agent", "--no-leader", "stdio"]);++ let mut deep = super::super::CliSpec::new(grok_config(), quiet, false, None);+ deep.deep = true;+ deep.builder = Some(super::super::Builder { investigation: None, inbox: std::env::temp_dir() });+ let Some(build) = super::super::acp_for(&deep) else { panic!("a deep build is allowed") };+ assert!(build.access_error.is_none() && build.validation_error.is_none());+ assert_eq!(build.args, ["agent", "--no-leader", "stdio"]);++ let blocked = crate::BackendOptions { args: vec!["--always-approve".into()], ..Default::default() };+ let Some(refused) = super::super::acp_for(&super::super::CliSpec::new(grok_config(), blocked, false, None)) else { panic!("Grok speaks ACP") };+ assert_eq!(refused.args, ["agent", "--no-leader", "stdio"]);+ assert!(refused.validation_error.is_some());++ let mut remote = grok_config();+ remote.ssh_host = Some("other-computer".into());+ assert!(super::super::acp_for(&super::super::CliSpec::new(remote, crate::BackendOptions::default(), false, None)).is_none());+ let off = crate::BackendOptions { acp: Some(false), ..Default::default() };+ assert!(super::super::acp_for(&super::super::CliSpec::new(grok_config(), off, false, None)).is_none());+ }++ fn grok_config() -> crate::BackendConfig {+ crate::BackendConfig { name: "Grok".into(), kind: crate::BackendKind::AgentCli, model: "grok".into(), base_url: None, ssh_host: None, enabled: true }+ }++ fn session_opened(model: &str, effort: &str) -> String {+ json!({+ "jsonrpc": "2.0",+ "id": 2,+ "result": {+ "sessionId": "s-1",+ "models": {"currentModelId": model, "availableModels": [{"modelId": "grok-4.7"}, {"modelId": "grok-4.6"}]},+ "configOptions": [+ {"id": "model", "currentValue": model, "options": [{"value": "grok-4.7", "name": "Grok 4.7"}, {"value": "grok-4.6", "name": "Grok 4.6"}]},+ {"id": "reasoning_effort", "category": "thought_level", "currentValue": effort, "options": [{"value": "low", "name": "Low"}, {"value": "high", "name": "High"}]}+ ]+ }+ })+ .to_string()+ }++ fn config_reply(id: u64, model: &str, effort: &str) -> String {+ json!({+ "jsonrpc": "2.0",+ "id": id,+ "result": {"configOptions": [+ {"id": "model", "currentValue": model},+ {"id": "reasoning_effort", "currentValue": effort, "options": [{"value": "low", "name": "Low"}, {"value": "medium", "name": "Medium"}, {"value": "high", "name": "High"}]}+ ]}+ })+ .to_string()+ }++ /// The CLI model flag does not stick after `session/new`. Overrides go out before the prompt,+ /// a value the session already has is skipped, and the session id is kept.+ #[test]+ fn session_config_is_applied_before_the_prompt_and_a_matching_value_is_skipped() {+ let mut c = core(None);+ c.config_queue = VecDeque::from([("model".into(), "grok-4.6".into()), ("reasoning_effort".into(), "low".into())]);+ c.prompt("Build it.");+ c.line(r#"{"jsonrpc":"2.0","id":1,"result":{"agentCapabilities":{"loadSession":true}}}"#);+ let first = sent(&c.line(&session_opened("grok-4.7", "high")));+ assert_eq!(first[0]["method"], "session/set_config_option");+ assert_eq!(first[0]["params"], json!({"sessionId": "s-1", "configId": "model", "value": "grok-4.6"}));+ assert!(!c.ready, "the picker waits until the override lands");+ assert_eq!(c.models, ["grok-4.7", "grok-4.6"]);+ let second = sent(&c.line(&config_reply(3, "grok-4.6", "high")));+ assert_eq!(second[0]["params"], json!({"sessionId": "s-1", "configId": "reasoning_effort", "value": "low"}));+ assert_eq!(c.current_model, "grok-4.6");+ assert_eq!(c.session_id().as_deref(), Some("s-1"), "a config reply does not carry the session id");+ let prompt = sent(&c.line(&config_reply(4, "grok-4.6", "low")));+ assert_eq!(prompt[0]["method"], "session/prompt");+ assert_eq!(prompt[0]["params"]["prompt"][0]["text"], "Build it.");+ assert!(c.ready);+ assert_eq!(c.models, ["grok-4.7", "grok-4.6"], "the session's model list stays");++ let mut same = core(None);+ same.config_queue = VecDeque::from([("model".into(), "grok-4.7".into()), ("reasoning_effort".into(), "low".into())]);+ same.prompt("Hi");+ same.line(r#"{"jsonrpc":"2.0","id":1,"result":{}}"#);+ let only_effort = sent(&same.line(&session_opened("grok-4.7", "high")));+ assert_eq!(only_effort.len(), 1);+ assert_eq!(only_effort[0]["params"]["configId"], "reasoning_effort");+ assert_eq!(only_effort[0]["params"]["value"], "low");++ let mut failed = core(None);+ failed.config_queue = VecDeque::from([("model".into(), "missing".into())]);+ failed.prompt("Hi");+ failed.line(r#"{"jsonrpc":"2.0","id":1,"result":{}}"#);+ failed.line(&session_opened("grok-4.7", "high"));+ let outs = failed.line(r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"unknown model"}}"#);+ assert_eq!(failed.failure, Some(TurnFailure::new(FailureKind::Configuration)));+ assert!(outs.contains(&Out::TurnEnded));+ assert!(!failed.ready);+ assert!(sent(&outs).is_empty(), "a failed override does not prompt");}#[test]diff --git a/crates/ai/src/cli_agents/adapters.rs b/crates/ai/src/cli_agents/adapters.rsindex 0d2a155a..d73b318e 100644--- a/crates/ai/src/cli_agents/adapters.rs+++ b/crates/ai/src/cli_agents/adapters.rs@@ -8,12 +8,14 @@ use super::*;mod antigravity;mod copilot;mod dsh;+mod grok;mod hermes;mod maki;mod opencode;pub use antigravity::Antigravity;pub use copilot::Copilot;pub use dsh::DeepSeekHarness;+pub use grok::Grok;pub use hermes::Hermes;pub use maki::Maki;pub use opencode::OpenCode;@@ -86,11 +88,38 @@ pub trait AgentAdapter: Send + Sync {fn acp_mcp_options(&self, _mcp: &McpCommand) -> Vec<String> {Vec::new()}+ /// Include `"type": "stdio"` on the MCP server in `session/new`. Grok's server enum requires+ /// it. Other agents leave it off, so a session that has not been checked with the field+ /// stays on the payload it already accepts.+ fn acp_mcp_stdio_type(&self) -> bool {+ false+ }+ /// Arguments after the ACP mode words and the model flag, still before a trailing subcommand.+ /// The default adds none, so agents whose flags already sit in [`acp_options`](Self::acp_options)+ /// stay unchanged.+ fn acp_mode_options(&self, _options: &BackendOptions, _access: Access) -> Vec<String> {+ Vec::new()+ }+ /// Words after every other ACP argument. Grok Build needs `stdio` last.+ fn acp_trailing(&self) -> &'static [&'static str] {+ &[]+ }+ /// Session options applied with `session/set_config_option` after the session opens, in order,+ /// before the conversation is ready. Each value is sent as a JSON string. The default sets none.+ fn acp_session_config(&self, _options: &BackendOptions) -> Vec<(String, String)> {+ Vec::new()+ }/// Refuse backend options that could bypass this adapter's restrictions, before its ACP/// process starts. The refusal is kept on the conversation and reported by `send`.fn validate_options(&self, _options: &BackendOptions) -> Result<(), ToolError> {Ok(())}+ /// Refuse an access mode this agent cannot hold. The default allows every mode. A refusal+ /// is kept beside [`validate_options`](Self::validate_options) and reported by `send`.+ /// Model-list discovery sends no prompt, so it does not apply this check.+ fn validate_access(&self, _access: Access) -> Result<(), ToolError> {+ Ok(())+ }/// The model shown in Settings: an explicit choice or the CLI's own default. `None` means/// the agent picks its model and doesn't offer a model selector here.fn model_in_use(&self, _options: Option<&BackendOptions>) -> Option<String> {@@ -231,7 +260,7 @@ impl Default for AgentAdapters {}impl AgentAdapters {- /// The built-in coding agents, including Copilot's ACP-only adapter.+ /// The built-in coding agents, including the ACP-only Copilot and Grok Build adapters.pub fn built_in() -> AgentAdapters {AgentAdapters {adapters: vec![@@ -243,6 +272,7 @@ impl AgentAdapters {Arc::new(Hermes),Arc::new(Maki),Arc::new(Copilot),+ Arc::new(Grok),Arc::new(DeepSeekHarness),],}diff --git a/crates/ai/src/cli_agents/adapters/grok.rs b/crates/ai/src/cli_agents/adapters/grok.rsnew file mode 100644index 00000000..37a8baa3--- /dev/null+++ b/crates/ai/src/cli_agents/adapters/grok.rs@@ -0,0 +1,429 @@+//! The person's installed Grok Build CLI, driven over ACP (`grok agent stdio`). Sign-in stays in+//! `grok login`. Craft Anything checks that an auth file exists and does not read it.++use super::*;+use std::ffi::OsStr;+use std::path::{Path, PathBuf};++/// Grok Build's ACP-only adapter. `acp = false` or an SSH host fails closed: the plain runner+/// would open the interactive TUI, which has no approval channel back to Craft Anything.+pub struct Grok;++impl AgentAdapter for Grok {+ fn ids(&self) -> &'static [&'static str] {+ &["grok"]+ }++ fn args(&self, _cx: &ArgsCx) -> Vec<String> {+ // The native runner refuses `requires_acp` before it asks for arguments.+ Vec::new()+ }++ fn requires_acp(&self) -> bool {+ true+ }++ fn has_model_catalog(&self) -> bool {+ true+ }++ /// Reasoning levels differ by model, so a model change has to open that model again.+ fn model_catalog_depends_on_selection(&self) -> bool {+ true+ }++ fn model_catalog(+ &self,+ config: &BackendConfig,+ options: &BackendOptions,+ directory: Option<&Path>,+ stop: &Stop,+ ) -> Result<Vec<models::AgentModel>, ToolError> {+ let metadata = super::super::acp_model_metadata(config, options, directory, stop)?;+ Ok(catalogue(&metadata, options))+ }++ fn validate_model(&self, config: &BackendConfig, options: &BackendOptions, directory: Option<&Path>, stop: &Stop) -> Result<(), ToolError> {+ stop.check()?;+ self.validate_options(options)?;+ if options.cli_model.is_none() && options.cli_thinking.is_none() {+ return Ok(());+ }+ models::validate(options, &self.model_catalog(config, options, directory, stop)?)+ }++ fn plain_fallback(&self) -> bool {+ false+ }++ fn answers_questions(&self) -> bool {+ true+ }++ fn model_in_use(&self, options: Option<&BackendOptions>) -> Option<String> {+ Some(+ options+ .and_then(|options| options.cli_model.as_deref().map(str::trim).filter(|model| !model.is_empty()).map(str::to_string))+ .unwrap_or_else(|| "Grok Build default".into()),+ )+ }++ fn model_choices(&self, config: &BackendConfig, options: &BackendOptions) -> Result<Vec<String>, ToolError> {+ Ok(self.model_catalog(config, options, None, &Stop::default())?.into_iter().map(|model| model.id).collect())+ }++ /// Reasoning is the shared thinking picker. Grok advertises no context window, and the+ /// Copilot context control would invent Standard and Extended tiers, so it stays off.+ fn supports_model_tuning(&self) -> bool {+ false+ }++ fn check_tool_server(&self, stop: &CancelToken) -> Result<(), ToolError> {+ cli_can_start(craft_anything_platform::self_cli_path().as_deref(), stop)+ }++ /// Extra arguments would land before `agent` and can request blanket approval. Supported+ /// settings are passed after `agent` by [`acp_mode_options`](Self::acp_mode_options).+ fn acp_options(&self, _options: &BackendOptions, _access: Access) -> Vec<String> {+ Vec::new()+ }++ fn validate_options(&self, options: &BackendOptions) -> Result<(), ToolError> {+ if options.args.is_empty() {+ Ok(())+ } else {+ Err(ToolError::invalid("Extra Grok arguments could bypass Craft Anything's approval checks.")+ .with_remediation("Remove this backend's extra arguments. Set its program, model and thinking through the backend options instead."))+ }+ }++ /// `grok agent` accepts no flag that stops native reads or writes, and a read does not ask+ /// permission. A saved permission or an always-approve setting can also edit without+ /// `session/request_permission`. Clean room, deep chat, and questions promise limits this+ /// agent cannot keep, so they are refused. A deep build may read, and an edit is gated only+ /// when Grok sends that request. Nothing here can force the request: the flags do not+ /// constrain `grok agent`, and replacing the person's Grok config would drop their servers.+ fn validate_access(&self, access: Access) -> Result<(), ToolError> {+ match access {+ Access::Build => Ok(()),+ Access::Analyse | Access::CleanRoomAnalyse | Access::CleanRoomBuild | Access::CleanRoomQuestion | Access::Question => {+ Err(ToolError::invalid("Grok Build reads and edits without asking, so a Clean room run, a deep chat, or a question can't hold it back.")+ .with_remediation("Use a deep build. Grok asks before an edit only when its own permission mode sends a request."))+ }+ }+ }++ fn acp_mode_options(&self, options: &BackendOptions, _access: Access) -> Vec<String> {+ // `--no-leader` keeps this run off the person's shared Grok session, including one+ // already open in a terminal. Effort after `agent` is what the CLI actually applies.+ let mut args = vec!["--no-leader".to_string()];+ if let Some(effort) = chosen_effort(options) {+ args.extend(["--reasoning-effort".into(), effort]);+ }+ args+ }++ fn acp_trailing(&self) -> &'static [&'static str] {+ &["stdio"]+ }++ /// Grok rejects a server object that has no `type`. Other agents do not send this field.+ fn acp_mcp_stdio_type(&self) -> bool {+ true+ }++ fn acp_session_config(&self, options: &BackendOptions) -> Vec<(String, String)> {+ // Model first. Switching model can reset the effort the CLI flag just set, so the+ // effort override is sent again afterwards.+ let mut config = Vec::new();+ if let Some(model) = options.cli_model.as_deref().map(str::trim).filter(|model| !model.is_empty()) {+ config.push(("model".into(), model.to_string()));+ }+ if let Some(effort) = chosen_effort(options) {+ config.push(("reasoning_effort".into(), effort));+ }+ config+ }++ fn sign_in_fix(&self) -> Option<String> {+ Some("Sign in with `grok login` in a terminal, then try again. Grok keeps the sign-in; Craft Anything never sees it.".into())+ }++ fn signed_in(&self, _program: &str) -> Option<bool> {+ let grok_home = std::env::var_os("GROK_HOME");+ // Existence only. The file holds the person's credentials and is not read.+ // Missing is unknown: `XAI_API_KEY` can authenticate with no auth.json, and the run reports it.+ auth_present(auth_path(grok_home.as_deref(), dirs::home_dir().as_deref()))+ }+}++/// `Some(true)` when `auth.json` exists as a file. Missing, or not a file, is unknown (`None`),+/// not "signed out".+fn auth_present(path: Option<PathBuf>) -> Option<bool> {+ path.and_then(|path| path.is_file().then_some(true))+}++/// `GROK_HOME/auth.json` when that variable is set, otherwise `~/.grok/auth.json`.+fn auth_path(grok_home: Option<&OsStr>, user_home: Option<&Path>) -> Option<PathBuf> {+ let dir = match grok_home {+ Some(home) if !home.is_empty() => PathBuf::from(home),+ _ => user_home?.join(".grok"),+ };+ Some(dir.join("auth.json"))+}++/// Thinking depth, in the same order Copilot uses: an explicit picker choice, then a saved+/// named effort, then the older `effort` field.+fn chosen_effort(options: &BackendOptions) -> Option<String> {+ options+ .cli_thinking+ .map(|effort| effort.as_str().to_string())+ .or_else(|| options.cli_reasoning_effort.map(|effort| effort.as_str().to_string()))+ .or_else(|| options.effort.map(|effort| effort.as_str().to_string()))+}++fn catalogue(metadata: &super::super::acp::ModelMetadata, options: &BackendOptions) -> Vec<models::AgentModel> {+ let tuning = crate::model_options::ModelTuning::from_metadata(metadata.current_model.clone(), &metadata.config_options);+ let active = options.cli_model.as_deref().map(str::trim).filter(|model| !model.is_empty()).unwrap_or(metadata.current_model.as_str());+ let thinking: Vec<_> = tuning.reasoning.iter().filter_map(|choice| crate::Effort::parse(choice.value.as_str())).collect();+ let mut ids = metadata.models.clone();+ if !metadata.current_model.is_empty() {+ ids.push(metadata.current_model.clone());+ }+ let mut ordered = Vec::new();+ for id in ids {+ if !id.is_empty() && !ordered.contains(&id) {+ ordered.push(id);+ }+ }+ ordered.into_iter().map(|id| models::AgentModel { name: id.clone(), thinking: if id == active { thinking.clone() } else { Vec::new() }, id }).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn grok_is_acp_only_and_registered() {+ let adapter = AgentAdapters::built_in().for_agent("grok");+ assert!(adapter.ids().contains(&"grok"));+ assert!(adapter.requires_acp() && !adapter.plain_fallback() && adapter.answers_questions());+ assert!(adapter.has_model_catalog() && adapter.model_catalog_depends_on_selection());+ assert!(!adapter.supports_model_tuning());+ assert_eq!(adapter.acp_trailing(), &["stdio"]);+ assert!(adapter.acp_mcp_stdio_type());+ assert!(!AgentAdapters::built_in().for_agent("maki").acp_mcp_stdio_type());+ assert_eq!(super::super::acp::acp_args("grok"), Some(&["agent"][..]));+ assert_eq!(super::super::acp::model_args("grok", Some("grok-4.5")), ["--model", "grok-4.5"]);+ assert!(super::super::acp::model_args("grok", Some(" ")).is_empty());+ }++ #[test]+ fn mode_flags_follow_agent_and_never_approve_everything() {+ let defaults = BackendOptions::default();+ assert_eq!(Grok.acp_mode_options(&defaults, Access::Question), ["--no-leader"]);+ assert!(Grok.acp_options(&defaults, Access::Build).is_empty());+ assert!(Grok.acp_session_config(&defaults).is_empty());+ let options = BackendOptions {+ cli_model: Some(" grok-4.6 ".into()),+ cli_thinking: Some(crate::Effort::Low),+ cli_reasoning_effort: Some(crate::config::CliReasoningEffort::High),+ effort: Some(crate::Effort::Medium),+ args: vec!["--always-approve".into()],+ ..Default::default()+ };+ // The saved extra arguments are refused and are not copied in front of `agent`.+ assert!(Grok.validate_options(&options).is_err());+ assert!(Grok.acp_options(&options, Access::Build).is_empty());+ assert_eq!(Grok.acp_mode_options(&options, Access::Build), ["--no-leader", "--reasoning-effort", "low"]);+ assert_eq!(Grok.acp_session_config(&options), [("model".into(), "grok-4.6".into()), ("reasoning_effort".into(), "low".into())]);+ assert!(!Grok.acp_mode_options(&options, Access::CleanRoomBuild).iter().any(|arg| arg.contains("always-approve")));+ for access in [Access::Analyse, Access::CleanRoomAnalyse, Access::CleanRoomBuild, Access::CleanRoomQuestion, Access::Question] {+ let error = Grok.validate_access(access).expect_err("clean room, deep chat, and questions are refused");+ assert!(error.message.contains("Clean room") && error.message.contains("deep chat") && error.message.contains("question"), "{}", error.message);+ assert!(error.remediation.as_deref().is_some_and(|fix| fix.contains("deep build")));+ }+ assert!(Grok.validate_access(Access::Build).is_ok());+ let named =+ BackendOptions { cli_reasoning_effort: Some(crate::config::CliReasoningEffort::Xhigh), effort: Some(crate::Effort::Low), ..Default::default() };+ assert_eq!(Grok.acp_session_config(&named), [("reasoning_effort".into(), "xhigh".into())]);+ assert_eq!(Grok.model_in_use(None).as_deref(), Some("Grok Build default"));+ assert_eq!(Grok.model_in_use(Some(&options)).as_deref(), Some("grok-4.6"));+ let fix = Grok.sign_in_fix().unwrap();+ assert!(fix.contains("grok login") && fix.contains("never sees"));+ }++ #[test]+ fn catalogue_offers_only_the_selected_models_advertised_thinking() {+ let metadata = super::super::acp::ModelMetadata {+ models: vec!["grok-4.7".into(), "grok-4.5".into()],+ current_model: "grok-4.7".into(),+ config_options: vec![json!({"id": "reasoning_effort", "options": [+ {"value": "low", "name": "Low"},+ {"value": "medium", "name": "Medium"},+ {"value": "high", "name": "High"},+ {"value": "xhigh", "name": "High"},+ {"value": "unsupported", "name": "Unknown"}+ ]})],+ };+ let mut options = BackendOptions { cli_model: Some("grok-4.5".into()), ..Default::default() };+ let models = catalogue(&metadata, &options);+ assert!(models.iter().all(|model| model.id != "auto"));+ assert_eq!(models.iter().map(|model| model.id.as_str()).collect::<Vec<_>>(), ["grok-4.7", "grok-4.5"]);+ assert!(models.iter().find(|model| model.id == "grok-4.7").unwrap().thinking.is_empty());+ options.cli_model = Some("grok-4.7".into());+ let models = catalogue(&metadata, &options);+ assert_eq!(+ models.iter().find(|model| model.id == "grok-4.7").unwrap().thinking,+ [crate::Effort::Low, crate::Effort::Medium, crate::Effort::High, crate::Effort::Xhigh]+ );+ options.cli_thinking = Some(crate::Effort::Xhigh);+ assert!(models::validate(&options, &models).is_ok());+ options.cli_thinking = Some(crate::Effort::Max);+ assert!(models::validate(&options, &models).is_err());+ }++ #[test]+ fn auth_path_uses_grok_home_and_does_not_need_the_real_one() {+ let custom = PathBuf::from("/tmp/grok-home");+ assert_eq!(auth_path(Some(custom.as_os_str()), None), Some(custom.join("auth.json")));+ let user = PathBuf::from("/home/u");+ assert_eq!(auth_path(Some(OsStr::new("")), Some(&user)), Some(user.join(".grok").join("auth.json")));+ assert_eq!(auth_path(None, Some(&user)), Some(user.join(".grok").join("auth.json")));+ assert_eq!(auth_path(None, None), None);+ }++ #[test]+ fn a_missing_auth_file_is_unknown_and_an_existing_file_is_signed_in() {+ let root = std::env::temp_dir().join(format!("craft-grok-auth-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(&root).unwrap();+ let file = root.join("auth.json");+ // Not a credential. The check is existence only, and this file is empty.+ assert_eq!(auth_present(Some(file.clone())), None);+ std::fs::write(&file, b"").unwrap();+ assert_eq!(auth_present(Some(file.clone())), Some(true));+ std::fs::remove_file(&file).unwrap();+ std::fs::create_dir(&file).unwrap();+ assert_eq!(auth_present(Some(file)), None);+ assert_eq!(auth_present(None), None);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// One real deep build: our MCP server is called, and one permission request is answered.+ /// Grok's home for this process is a temporary ask-mode config, so a shell write asks even+ /// when the person's own config would approve every tool. That config is not modified.+ /// Not part of the default suite.+ #[test]+ #[ignore = "live Grok Build session; needs grok signed in and craft-anything-cli built"]+ #[cfg(unix)]+ fn a_live_build_connects_tools_and_answers_one_permission() {+ use std::os::unix::fs::PermissionsExt;+ let pid = std::process::id();+ let root = std::env::temp_dir().join(format!("craft-grok-live-{pid}"));+ let home = std::env::temp_dir().join(format!("craft-grok-home-{pid}"));+ let _keep_root = RemoveOnDrop(root.clone());+ let _keep_home = RemoveOnDrop(home.clone());+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&home);+ std::fs::create_dir_all(root.join("inbox")).unwrap();+ std::fs::create_dir_all(&home).unwrap();+ std::fs::write(root.join("readme.txt"), "live check\n").unwrap();+ // Ask, and no personal MCP servers. `ui.permission_mode` is what the CLI reads.+ std::fs::write(+ home.join("config.toml"),+ "[ui]\npermission_mode = \"ask\"\nyolo = false\n\n[auto_mode]\nenabled = false\n\ndefault_auto_mode = false\ndisable_web_search = true\n\n[cli]\nauto_update = false\nuse_leader = false\n",+ )+ .unwrap();+ let user_home = dirs::home_dir().expect("a home directory");+ let auth = user_home.join(".grok").join("auth.json");+ assert!(auth.is_file(), "this live check needs an existing grok auth file; it is not read");+ std::os::unix::fs::symlink(&auth, home.join("auth.json")).unwrap();+ let listed = std::process::Command::new("sh").arg("-c").arg("command -v grok").output().expect("look up grok");+ let found = String::from_utf8_lossy(&listed.stdout).trim().to_string();+ let grok_bin = if found.is_empty() { user_home.join(".grok").join("bin").join("grok") } else { PathBuf::from(found) };+ assert!(grok_bin.is_file(), "grok has to be installed for this live check");+ let wrapper = root.join("grok-ask");+ let script = format!("#!/bin/sh\nexport GROK_HOME='{}'\nexec '{}' \"$@\"\n", home.display(), grok_bin.display());+ std::fs::write(&wrapper, script).unwrap();+ std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();+ let _ = std::process::Command::new("git").arg("-C").arg(&root).arg("init").output();++ let permissions = std::sync::Arc::new(craft_anything_platform::sync::Mutex::new(Vec::<String>::new()));+ let record = permissions.clone();+ let approver: super::super::acp::Approver = std::sync::Arc::new(move |tool: &str, _input: &serde_json::Value| {+ record.lock().unwrap().push(tool.to_string());+ true+ });+ let mut spec = super::super::CliSpec::new(+ crate::BackendConfig {+ name: "Grok".into(),+ kind: crate::BackendKind::AgentCli,+ model: "grok".into(),+ base_url: None,+ ssh_host: None,+ enabled: true,+ },+ BackendOptions { command: Some(wrapper.display().to_string()), ..Default::default() },+ false,+ Some(root.clone()),+ );+ // Deep build: Clean room is refused, because Grok's native reads never ask.+ spec.deep = true;+ spec.builder = Some(super::super::Builder { investigation: Some(root.clone()), inbox: root.join("inbox") });+ let mut conv = super::super::builder_conversation(spec, approver);+ conv.send(+ "Do exactly these two things in this folder, then stop. First call the craft-anything MCP tool core_session_show and no other MCP server. Then run this shell command and no other command: mkdir grok-live-marker",+ );++ let started = std::time::Instant::now();+ let mut tools = Vec::new();+ let mut notes = Vec::new();+ let mut errors = Vec::new();+ let mut done = false;+ let mut saw_server = false;+ while started.elapsed() < std::time::Duration::from_secs(180) {+ for event in conv.poll() {+ match event {+ crate::AgentEvent::ToolStarted { tool, input, .. } => {+ let blob = format!("{tool} {input}");+ let lower = blob.to_ascii_lowercase();+ if lower.contains("session_show") || lower.contains("craft-anything") || lower.contains("craft_anything") {+ saw_server = true;+ }+ let mut note = blob.chars().take(160).collect::<String>();+ note = note.replace(&user_home.display().to_string(), "~");+ notes.push(note);+ tools.push(tool);+ }+ crate::AgentEvent::ToolFinished { tool, .. } => tools.push(tool),+ crate::AgentEvent::Error { message, .. } => errors.push(message),+ crate::AgentEvent::TurnDone { .. } => done = true,+ crate::AgentEvent::ConsentNeeded { call_id, tool, .. } => {+ permissions.lock().unwrap().push(tool);+ conv.answer_consent(&call_id, true);+ }+ _ => {}+ }+ }+ if done && !conv.is_busy() {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ conv.stop();+ let asked = permissions.lock().unwrap().clone();+ assert!(done, "the turn did not finish; tools={tools:?} permissions={asked:?} notes={notes:?} errors={errors:?}");+ assert!(!asked.is_empty(), "no permission was answered; tools={tools:?} notes={notes:?} errors={errors:?}");+ assert!(saw_server, "craft-anything's tools did not run; tools={tools:?} permissions={asked:?} notes={notes:?} errors={errors:?}");+ }++ #[cfg(unix)]+ struct RemoveOnDrop(PathBuf);+ #[cfg(unix)]+ impl Drop for RemoveOnDrop {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }+}diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rsindex a0a42e32..d0e751c4 100644--- a/crates/ai/src/cli_agents/mod.rs+++ b/crates/ai/src/cli_agents/mod.rs@@ -42,6 +42,7 @@ pub const KNOWN: &[(&str, &str, &str)] = &[("claude-code", "claude", "Claude Code"),("codex", "codex", "Codex"),("copilot", "copilot", "GitHub Copilot"),+ ("grok", "grok", "Grok Build"),("gemini-cli", "gemini", "Gemini CLI"),("antigravity", "agy", "Antigravity"),("opencode", "opencode", "OpenCode"),@@ -611,27 +612,28 @@ fn acp_for(spec: &CliSpec) -> Option<AcpConversation> {let acp_args = selected_acp_args(adapter.as_ref(), &agent, &spec.options).filter(|_| local)?;// No program to start: the plain run reports why.let program = program_of(&spec.config, &spec.options).ok()?;- let access = match (spec.question, spec.deep, spec.builder.is_some()) {- (true, true, _) => Access::Question,- (true, false, _) => Access::CleanRoomQuestion,- (false, true, true) => Access::Build,- (false, false, true) => Access::CleanRoomBuild,- _ => Access::Analyse,- };+ // Same modes as the plain runner, including Clean room chat (no builder, not deep).+ let access = access_for(spec.builder.is_some(), spec.deep, spec.question);let mut args = adapter.acp_options(&spec.options, access);args.extend(acp_args.iter().map(|a| a.to_string()));args.extend(acp::model_args(&agent, spec.options.cli_model.as_deref()));+ // After the mode words and model flag, still before a trailing subcommand (`stdio` for Grok).+ args.extend(adapter.acp_mode_options(&spec.options, access));let cwd = spec.project.clone().or_else(|| std::env::current_dir().ok()).unwrap_or_else(std::env::temp_dir);let mcp = mcp_for(spec, false);if !spec.question {args.extend(adapter.acp_mcp_options(&mcp));}+ args.extend(adapter.acp_trailing().iter().map(|word| (*word).to_string()));let preamble = spec.preamble.clone().unwrap_or_else(|| crate::prompt::cli_preamble(spec.beginner));+ let session_config = adapter.acp_session_config(&spec.options);Some(AcpConversation::new(&spec.config.name, &agent, program, args, cwd, mcp, if spec.question { None } else { spec.resume.clone() }).with_validation(adapter.validate_options(&spec.options))+ .with_access_limit(adapter.validate_access(access)).with_adapter(adapter).with_question(spec.question)+ .with_session_config(session_config).with_preamble(preamble).with_logs(spec.logs.clone()),)@@ -2422,7 +2424,7 @@ echo '{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}'reg.register(Arc::new(EchoAgent));assert_eq!(format!("{reg:?}"),- r#"["claude-code", "codex", "gemini-cli", "opencode", "antigravity", "hermes", "maki", "copilot", "dsh", "echo-agent"]"#+ r#"["claude-code", "codex", "gemini-cli", "opencode", "antigravity", "hermes", "maki", "copilot", "grok", "dsh", "echo-agent"]"#);}diff --git a/crates/ai/src/config.rs b/crates/ai/src/config.rsindex 7285110d..47a57771 100644--- a/crates/ai/src/config.rs+++ b/crates/ai/src/config.rs@@ -110,7 +110,7 @@ pub struct BackendOptions {#[serde(skip_serializing_if = "Option::is_none")]pub timeout_secs: Option<u64>,/// Agent CLIs that speak ACP (`cli_agents::acp::ACP_AGENTS`): chat over it, one agent process- /// per conversation (on for Copilot, off for other agents unless set).+ /// per conversation (on for Copilot and Grok Build, off for other agents unless set).#[serde(skip_serializing_if = "Option::is_none")]pub acp: Option<bool>,/// Agent CLIs that keep their sign-in, settings and sessions in a folder of their own (Claudediff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rsindex 933bbcf0..f09fcd72 100644--- a/crates/ai/src/lib.rs+++ b/crates/ai/src/lib.rs@@ -77,7 +77,7 @@ impl BackendKind {BackendKind::Openrouter => openai::OPENROUTER_MODELS,BackendKind::Gemini => openai::GEMINI_MODELS,BackendKind::OpenaiCompatible => &[],- BackendKind::AgentCli => &["claude-code", "codex", "copilot", "gemini-cli", "opencode", "antigravity", "hermes", "maki", "dsh"],+ BackendKind::AgentCli => &["claude-code", "codex", "copilot", "grok", "gemini-cli", "opencode", "antigravity", "hermes", "maki", "dsh"],}}diff --git a/crates/platform/src/which.rs b/crates/platform/src/which.rsindex 70a7a104..ab342dfa 100644--- a/crates/platform/src/which.rs+++ b/crates/platform/src/which.rs@@ -15,17 +15,19 @@ pub fn which_all(name: &str) -> Vec<PathBuf> {/// Folders, under the home folder and then system-wide, where coding agents, npm, Homebrew and/// other installers put command-line programs. OpenCode's installer uses `~/.opencode/bin`, or-/// `~/bin` when there is one (#112).+/// `~/bin` when there is one (#112). Grok Build's installer uses `~/.grok/bin`.#[cfg(unix)]-const USUAL_HOME_DIRS: &[&str] = &[".local/bin", ".claude/local", ".npm-global/bin", ".bun/bin", ".volta/bin", ".cargo/bin", ".opencode/bin", "bin"];+const USUAL_HOME_DIRS: &[&str] =+ &[".local/bin", ".claude/local", ".npm-global/bin", ".bun/bin", ".volta/bin", ".cargo/bin", ".opencode/bin", ".grok/bin", "bin"];#[cfg(unix)]const USUAL_DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/bin"];// Claude Code's installer, npm (without a custom prefix), WinGet's portable packages (Claude-// Code's WinGet install), bun, cargo and Hermes Agent's installer (`%LOCALAPPDATA%\hermes\bin`, #116);-// PATH may not have them yet in an app started before the install.+// Code's WinGet install), bun, cargo, Hermes Agent's installer (`%LOCALAPPDATA%\hermes\bin`, #116)+// and Grok Build (`%USERPROFILE%\.grok\bin`). PATH may not have them yet in an app started before+// the install.#[cfg(windows)]const USUAL_HOME_DIRS: &[&str] =- &[r".local\bin", r"AppData\Roaming\npm", r"AppData\Local\Microsoft\WinGet\Links", r".bun\bin", r".cargo\bin", r"AppData\Local\hermes\bin"];+ &[r".local\bin", r"AppData\Roaming\npm", r"AppData\Local\Microsoft\WinGet\Links", r".bun\bin", r".cargo\bin", r"AppData\Local\hermes\bin", r".grok\bin"];#[cfg(not(any(unix, windows)))]const USUAL_HOME_DIRS: &[&str] = &[];// WinGet's portable packages installed for every user (`--scope machine`).@@ -350,11 +352,27 @@ mod tests {assert_eq!(bins, [node.join("v20.10.0/bin"), node.join("v18.19.1/bin"), node.join("v9.11.2/bin")]);let dirs: Vec<PathBuf> = std::env::split_paths(&with_usual_dirs(None, Some(home.path().to_path_buf()), None).unwrap()).collect();assert!(dirs.contains(&home.path().join(".opencode/bin")));+ assert!(dirs.contains(&home.path().join(".grok/bin")));let at = |p: &Path| dirs.iter().position(|d| d == p).unwrap();assert!(at(&home.path().join(".cargo/bin")) < at(&bins[0]) && at(&bins[2]) < at(Path::new("/usr/local/bin")));assert!(nvm_bins(Path::new("/nowhere")).is_empty());}+ /// Grok Build installs `grok` in `~/.grok/bin`, which a Dock-launched app does not have on PATH.+ #[cfg(unix)]+ #[test]+ fn grok_in_its_home_bin_is_found() {+ let dir = tempfile::tempdir().unwrap();+ let home = dir.path().join("home");+ let bin = home.join(".grok/bin");+ std::fs::create_dir_all(&bin).unwrap();+ let program = bin.join("grok");+ std::fs::write(&program, b"#!/bin/sh\n").unwrap();+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();+ assert_eq!(which_in("grok", with_usual_dirs(None, Some(home), None)).as_slice(), std::slice::from_ref(&program));+ }+/// #116: Hermes Agent's Windows installer puts `hermes.exe` in `%LOCALAPPDATA%\hermes\bin` and/// adds that to the user's PATH, which an app started before the install (or by a launcher)/// doesn't have, so Settings found no Hermes.@@ -457,6 +475,7 @@ mod tests {assert!(dirs.contains(&home.join("AppData").join("Local").join("Antigravity")));// Each way Claude Code installs on Windows: native, npm, WinGet (per user and machine-wide).assert!(dirs.contains(&home.join(r"AppData\Local\Microsoft\WinGet\Links")));+ assert!(dirs.contains(&home.join(r".grok\bin")));assert!(dirs.contains(&PathBuf::from(r"C:\Program Files\WinGet\Links")));}diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 64150690..4dceaba8 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -591,6 +591,17 @@ Owner: open · Status: in progressdiscovery, MCP-only tool restrictions, model selection and fresh read-only questions;unit tests and CLI 1.0.105 with an isolated home and loopback model, all five access modes— claimed: qu-gg, branch `feature/r2.2-copilot-integration` (recorded during PR preparation)+- [x] Grok Build as a coding agent over ACP (`grok agent stdio`): discovery in `~/.grok/bin`,+ the person's own `grok login` (a missing `auth.json` is unknown, so an API key still+ starts), model and reasoning effort, and our MCP server on the session with `"type": "stdio"`+ only for Grok. Clean room, deep chat, and questions are refused, because Grok can read and+ edit without a permission request. Verified against Grok 1.0.77's ACP handshake and+ `session/set_config_option` (the CLI `--model` flag does not stick after `session/new`). A+ live deep build on 2026-11-06 (Grok 1.0.77) finished, called the Craft Anything server, and+ answered one permission request. Clean room and deep chat were not run live; those runs+ are refused.+ See [Grok Build](grok.md).+ — branch `feature/r2.2-grok-agent`- [x] Review hardening: cap target handoff at 128 while preserving the active target; propagatecontext-discovery cancellation, normalize CLI-only efforts for Claude requests, and namethe configured agent in shared picker warnings, with focused regressions and translationsdiff --git a/docs/STATUS.md b/docs/STATUS.mdindex 5e89f5d0..604dcfc8 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -93,6 +93,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| DeepSeek Harness builder | Runs the person's own `dsh --profile headless "<task>"`, which answers one task and prints its last message as text. The harness takes its tool servers from profile patch layers and has no per-run flag for one, so our tool server arrives as a generated `--patch` overlay for that run (the run's project, inbox and mode included); the person's own profile is untouched, a question gets no tool server, and its headless profile keeps no session to resume. An npm `.cmd` shim is unwrapped to its interpreter, so `dsh` found on PATH runs as `node …/dsh/lib/bin.js` | Adapter and YAML-overlay tests; live preflight (`ai test`); live builder turns on a website (follow-up build, 3 min 10 s, 100% alike at 1440/768/390 px, Ready) where the builder's own journal entries show `rebuild_check`, `core_unknown_add`, `core_plan_update` and `core_handoff_write` going through our tool server, and that server started with the run's `--project`/`--inbox`. Not checked: resume (none exists) and a build with the harness's desktop profile. Also verified on macOS arm64 (2026-11-07, DSH 0.2.2-rc.1, stored sign-in restored for the headless profile as its README describes): a static website reached Ready with one check pass, and the builder called our MCP tools || Agents over ACP | Opt-in per backend (`acp = true`): Gemini CLI, Qwen Code, opencode, goose, Hermes and Maki in their ACP mode, one agent process per chat or build with our MCP server; Maki's ACP mode takes the backend's model (`cli_model`). In chat, permission requests become consent questions; in builds they go through the same approval policy as Claude Code's (inbox, Auto mode). While a saved session loads, replayed updates are withheld from the new turn | Protocol unit tests against scripted agent messages and an approval-policy test. Run live with Maki 0.7.0 only (2026-11-02, Linux, headless CLI): a static page built to Ready in 38 s, a follow-up continued the same session with `session/load`, and with Auto mode off its command and tool requests were refused in an unattended run. Replay suppression passes scripted load-history, success/error and cancellation tests; this correction has not been rerun with a live agent. Turns report 0 tokens over ACP || GitHub Copilot | Installed `copilot` through ACP by default, with CLI-owned login (no credential import), explicit Craft Anything MCP tool allowlist, model selection and fresh read-only build questions. Target handoff retains the last 128 entries with the active target last; context discovery respects tool cancellation and shared picker warnings name the agent | Authenticated builds, model discovery and real-account session resume confirmed by the person using the app. Target-boundary, cancellation and agent-warning regressions supplement unit tests and an offline CLI 1.0.105 compatibility test covering all five access modes. See [copilot.md](copilot.md) |+| Grok Build | Installed `grok` through ACP by default (`grok agent --no-leader stdio`). Sign-in stays in `grok login`. An existing `auth.json` counts as signed in and is not read; a missing file is unknown, so the run itself reports an authentication problem. `XAI_API_KEY` is separate: detection reads it and the xAI API backend can use it; this adapter does not. Clean room, deep chat, and questions are refused, because Grok can read and edit without a permission request and `grok agent` has no flag that holds those modes. A deep build is allowed. The chosen model is applied with `session/set_config_option` after `session/new`, because the CLI `--model` flag does not survive that call. Reasoning effort is passed after `agent` and set again after the model. Our MCP server is attached on the session, and only this agent is sent `"type": "stdio"`. The person's own Grok MCP servers are not removed. Thinking uses the shared model picker; there is no context-window control. `acp = false` and SSH are refused | Scripted ACP tests for the argument order, `"type": "stdio"` on Grok's server only, and `session/set_config_option` before the prompt, including a value the session already has. `initialize`, `session/new` and `session/set_config_option` were checked against Grok 1.0.77. A live deep build on 2026-11-06 (Grok 1.0.77, temporary ask-mode home) finished, called the Craft Anything server, and answered one permission request. The person's own config was not changed. See [grok.md](grok.md) || Shared investigation for local agents | A worker saves session-only investigations before starting MCP, shares open targets in a mode-aware handoff, and reloads externally recorded evidence/findings. Builder refresh failures warn rather than ending the turn. The workbench Evidence pane shows `fnd_*` records with proof links; `core_finding_edit` preserves ids and omitted confidence while checking evidence and stale revisions | Engine persistence/correction tests, process-level MCP target tests in both modes, and headless findings-rendering test; live authenticated target-to-finding workflow confirmed by the person using the app || Copilot model options | Shared agent catalogue, model/thinking picker, `cli_model`/`cli_thinking` and `ai_models_list`/`ai_model_set`; selected-model reasoning metadata reloads without a prompt. Context tiers remain separate through `ai_model_options_show`/`ai_model_options_set`, preserving thinking. Legacy reasoning settings remain readable | Isolated catalogue/validation, flags, persistence, stale-result and headless UI tests. Previous authenticated metadata checks used CLI 1.0.105; no new live-account run after the shared-picker rework. Numeric context limits are not advertised in its initial ACP metadata || Investigation writer coordination | Every project-backed mutation holds one OS file lock over load, revision validation, mutation and state/Markdown writes. Waits are bounded and cancellable; unreadable state is not overwritten | Separate-process append/revision-race tests, matching Markdown renders, lock timeout/cancellation/release and malformed-state regressions |@@ -327,6 +328,17 @@ launch or preview was run for this documentation correction.runs with `--auto`; Hermes's `-z` turns its approvals off on every run, chats included, so a Hermeschat isn't limited to analysing and Clean room's approval rule doesn't reach it. Hermes is opt-inand hasn't been run live here.+- Grok Build (`grok agent stdio`) is offered when `grok` is installed and speaks ACP by default.+ Model and reasoning effort are set again with `session/set_config_option` after `session/new`,+ because the CLI `--model` flag does not stick; `--reasoning-effort` is also passed after `agent`.+ Our MCP server is added on the session. `"type": "stdio"` is sent only for Grok. The person's own Grok MCP servers stay+ available. Clean room, deep chat, and questions are refused: a native read does not ask permission, and a saved permission can edit+ without a request. A deep build is allowed, and an edit is gated only when Grok sends `session/request_permission`.+ A missing `auth.json` is unknown, so an API key is not blocked. Checked+ against Grok 1.0.77: `initialize`, `session/new` and `session/set_config_option`. A live deep build+ on 2026-11-06 finished, called the Craft Anything server, and answered one permission request under a+ temporary ask-mode home. The person's own config was not changed. A config that approves every tool does not ask.+ See [grok.md](grok.md).- Maki (`maki -p`, or over ACP with `acp = true`) is offered when adding a coding agent and found byDetect. Over ACP it asks us before commands, our own tools and writes outside its working folder;writes inside that folder (a build's project folder, our own records included) and every readdiff --git a/docs/extending.md b/docs/extending.mdindex f2a705a0..39bc373e 100644--- a/docs/extending.md+++ b/docs/extending.md@@ -12,7 +12,7 @@ place to add yours. Follow `AGENTS.md` (never crash, layers, external programs t| A way to judge a build | `crates/ai/src/rebuild/kinds/` | Implement `Check` (`run(&mut CheckCx) -> CheckResult`; `applies` to skip it in some runs, or wrap it in `DeepOnly`); return it from your kind's `checks`. Decide on `passed`/`similarity`, never on text. || A stack | `crates/ai/src/rebuild/stacks.toml` | One `[[stack]]` entry: name, the builder's steps, the phrases that ask for it, its engine, the package.json or Cargo.toml dependencies that show a build uses it, the files that show a person's own folder is built with it. A component or styling library is a `[[library]]` entry (name, phrases, the stacks it works with, steps). || A way to build, test or launch a project | `crates/engine/src/toolchains.toml` | One `[[toolchain]]` entry: name, marker files, build/test commands, no-tests messages and optional `launch` recipes. Earlier markers win; `standalone_entrypoints` detects script-only projects only after every manifest has been checked. Each launch recipe has a root `file` and argv `command`; `{file}` substitutes the matching relative filename without a shell. A wildcard entrypoint must match exactly one file within the bounded scan. `local_programs` and `windows_program` apply to build, test and launch. Packaged programs, Electron and Godot keep priority. AI's `stacks::Toolchain` and `toolchain_in` re-export this shared catalogue. |-| A coding agent | `crates/ai/src/cli_agents/adapters.rs` | Implement `AgentAdapter` (args, required flags, stream parsing, resume, sign-in check) and register it in `AgentAdapters`. Use `has_model_catalog`, `model_catalog`, `validate_model` and the shared `AgentModel`/`ModelContext` picker and tools for model/thinking selection; set `model_catalog_depends_on_selection` when metadata depends on the selected model. ACP agents also get a row in `cli_agents::acp::ACP_AGENTS`; if their ACP mode takes the backend's model, a row in `ACP_MODEL_FLAGS` too. Override ACP startup options, process setup or `requires_acp` when needed; verify actual tool exposure, not only startup. |+| A coding agent | `crates/ai/src/cli_agents/adapters.rs` | Implement `AgentAdapter` (args, required flags, stream parsing, resume, sign-in check) and register it in `AgentAdapters`. Use `has_model_catalog`, `model_catalog`, `validate_model` and the shared `AgentModel`/`ModelContext` picker and tools for model/thinking selection; set `model_catalog_depends_on_selection` when metadata depends on the selected model. ACP agents also get a row in `cli_agents::acp::ACP_AGENTS`; if their ACP mode takes the backend's model, a row in `ACP_MODEL_FLAGS` too. Flags that belong after those mode words go in `acp_mode_options`, a trailing subcommand such as Grok Build's `stdio` in `acp_trailing`, and options applied with `session/set_config_option` after the session opens in `acp_session_config`. Set `acp_mcp_stdio_type` only when that agent's session list requires `"type": "stdio"` on our MCP server (Grok Build does; other agents do not). Refuse an access mode in `validate_access` when the agent cannot hold that mode (Grok Build refuses Clean room, deep chat, and questions). Override ACP startup options, process setup or `requires_acp` when needed; verify actual tool exposure, not only startup. || An asset provider | `crates/engines/src/assets/` | Implement `AssetProvider` (`key_env` names its environment variable); add its models and prices to `assets.toml`. Its key is its own: `assets_key_set` with `provider`, kept as `assets:<id>`. || An external engine | `crates/engines/src/table.rs` | One `ExternalEngine` entry (exes, known paths, what it's for, install pins with SHA-256 checked against the publisher), plus a `tool_paths!` id in `settings.rs` if people can point at their own install. || A front end for builds | anywhere above L5 | Hold a `rebuild::RunSet` (it queues past its limit) and `poll` it; test it with `RunSet::with_starter(StandIns::starter())`, whose runs report only what the test sends. |diff --git a/docs/grok.md b/docs/grok.mdnew file mode 100644index 00000000..cf038070--- /dev/null+++ b/docs/grok.md@@ -0,0 +1,108 @@+# Grok Build++Craft Anything can use the installed Grok Build CLI for a deep build through the+Agent Client Protocol (ACP). This is separate from the xAI API. When `XAI_API_KEY` is set,+Settings → AI also offers **xAI (Grok)** as an OpenAI-compatible server for questions.++## Setup++1. Install Grok Build. Its program is `grok`, usually in `~/.grok/bin` (or `%USERPROFILE%\.grok\bin`).+ Craft Anything looks there even when a desktop launch left that folder off `PATH`.+2. Sign in with `grok login`. Grok keeps that login in `auth.json`. Craft Anything checks+ whether the file exists and does not read it or sign in for you. When `auth.json` exists under+ `GROK_HOME`, or under `~/.grok` when that variable is unset, the app treats Grok as signed+ in. A missing file is unknown, so a build still starts and Grok reports an authentication+ problem itself. `XAI_API_KEY` is separate. Grok can use it when there is no `auth.json`.+ Settings → AI detection reads that variable, and the xAI API backend can use it. The Grok+ Build adapter does not read the key.+3. In Settings → AI, detect and add **Grok Build**, then choose it for **Build with this**.+ A chat and a question are refused. If `grok` is installed somewhere else, use **Choose...**+ and pick the program.++The equivalent backend entry in `config.toml` is:++```toml+[[ai.backends]]+name = "Grok Build"+kind = "agent_cli"+model = "grok"+enabled = true+```++`model` names the agent. ACP is on for this agent. Do not set `acp = false` or an SSH host:+those are refused rather than opening the interactive TUI, which has no way to ask Craft+Anything for approval. Extra `args` are refused too. They would be placed before `agent` and+could request blanket approval. There is no folder override: the run uses the sign-in Grok+already has on this computer.++## What runs++A deep build starts:++```sh+grok agent --model <cli_model> --no-leader --reasoning-effort <level> stdio+```++`--model` and `--reasoning-effort` are omitted when you have not chosen them. `--no-leader` is+always passed, so the run does not attach to a Grok session you already have open. `stdio`+comes last. Craft Anything does not pass `--always-approve`.++The CLI `--model` flag is visible while Grok starts, then `session/new` switches back to the+model saved in Grok. Craft Anything sets the chosen model again with `session/set_config_option`+before the session is ready, and sets the reasoning effort after that, because a model change+can reset it. The value on the wire is a string (`"grok-4.6"`, `"low"`), not a nested object.+If the session already has that value, the call is skipped.++## Model and thinking++Use the shared model and **Thinking depth** picker (Settings → AI → **Change...**), or set+`cli_model` and `cli_thinking` on the same backend entry. The list comes from the session's+advertised models. There is no `auto` entry and no context-window control: Grok does not+advertise one, and inventing Standard and Extended tiers would be wrong. Reasoning levels are+whatever that model lists (`low`, `medium`, `high`, `xhigh`, and so on). A level the model+does not list is refused. An older `cli_reasoning_effort` or `effort` value is still used when+`cli_thinking` is unset.++```toml+cli_model = "grok-4.6"+cli_thinking = "low"+```++Discovery sends no prompt. It does open a session long enough to read the model list and apply+`cli_model`, so the thinking choices match that model. That read is not a question run, so the+refusal below does not apply to it.++## Tools, MCP and Clean room++Builds attach Craft Anything's MCP server on `session/new` as a stdio server named+`craft-anything`, with `"type": "stdio"` because Grok's server list rejects an object that+has no type. That field is sent only for Grok. Grok also keeps the MCP servers from your own+Grok config. Craft Anything does not edit that config and cannot turn those servers off for+one run.++Clean room, deep chat, and questions are refused before Grok starts. `grok agent` does not+accept `--permission-mode`, `--deny`, or `--disallowed-tools`, and those flags do not+constrain the agent when they are placed before `agent`. A native read does not ask+permission, so Clean room cannot keep the original out of reach. A question must not change+files. Deep chat is only analysis, and a saved permission or an always-approve setting can+edit without a request, so that limit cannot be held either. A deep build is allowed: it may+read, and an edit is gated only when Grok sends `session/request_permission`. A Grok config+that approves every tool will still edit without asking. Craft Anything does not pass+`--always-approve`, and it does not replace the person's Grok config to force a prompt.++## What was checked++Against Grok Build 1.0.77: `initialize`, `session/new`, and `session/set_config_option` (a+string model id sticks; the CLI `--model` flag does not survive `session/new`;+`--reasoning-effort` after `agent` does stick and is sent again after a model change). The+argument order, the `type: stdio` server payload, and the config queue are covered by unit+tests with a scripted agent.++A live deep build was run on 2026-11-06 with Grok Build 1.0.77. The turn finished in about+30 seconds. A tool call named the `craft-anything` server or `core_session_show`, and one+permission request was answered with allow. That run used a temporary `GROK_HOME` whose+`ui.permission_mode` was `ask`, and a symlink to the existing auth file. The file was not+read, and the person's own Grok config was not changed. A config that approves every tool+does not send that request. Copilot, Gemini, and Maki were not checked live with+`"type": "stdio"`; the field is still sent only for Grok. Clean room and deep chat were+not run live, because those runs are refused.