Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
grok: explain an empty reply instead of returning nothing
Lin (kwant bot)c9e8adc758f6
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 271a948b..c190cd6a 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -237,6 +237,8 @@ struct GrokRun {/// grok's `error` events.errors: Vec<String>,stop_reason: Option<String>,+ /// `None` if grok was killed by a signal.+ exit_code: Option<i32>,}/// Reads a pipe to the end, keeping at most the last `max` bytes.@@ -297,7 +299,8 @@ impl CliDriver {let stdout_pipe = child.stdout.take();let stderr_pipe = child.stderr.take();let read_stdout = async {- let mut run = GrokRun { stdout: String::new(), stderr: String::new(), errors: Vec::new(), stop_reason: None };+ let mut run =+ GrokRun { stdout: String::new(), stderr: String::new(), errors: Vec::new(), stop_reason: None, exit_code: None };let mut parser = super::grok::StreamParser::default();let mut buffer = [0u8; 4096];// Bytes of a UTF-8 character split across reads@@ -334,7 +337,7 @@ impl CliDriver {}};let (mut run, stderr) = tokio::join!(read_stdout, read_stderr);- let _ = child.wait().await;+ run.exit_code = child.wait().await.ok().and_then(|s| s.code());drop(home);run.stderr = stderr;Ok(run)@@ -519,6 +522,24 @@ impl Driver for CliDriver {effective_prompt.clone(),];let (text, tokens) = match self.run_grok(&bin_path, &input, args, &event_tx).await {+ Ok(run) if run.stdout.trim().is_empty() => {+ // Never an empty reply: say why grok gave none+ let mut secrets = input.mcp.as_ref().map(|c| c.secret_values()).unwrap_or_default();+ secrets.extend(input.mcp.as_ref().and_then(|c| c.gateway.as_ref()).map(|g| g.token.clone()));+ let notice = super::grok::empty_reply_notice(+ &super::grok::EmptyRun {+ stderr: &run.stderr,+ errors: &run.errors,+ stop_reason: run.stop_reason.as_deref(),+ exit_code: run.exit_code,+ },+ &secrets,+ );+ tracing::warn!(exit_code = ?run.exit_code, stop_reason = ?run.stop_reason, "grok gave no reply");+ let msg = format!("⚠️ [{}] {notice}", input.kwant.name);+ let _ = event_tx.send(RuntimeEvent::TextDelta(msg.clone())).await;+ (msg, 0)+ }Ok(run) => {let tokens = run.stdout.len() / 4;(run.stdout, tokens)diff --git a/src/drivers/grok.rs b/src/drivers/grok.rsindex be2a27b3..64460ed2 100644--- a/src/drivers/grok.rs+++ b/src/drivers/grok.rs@@ -136,6 +136,88 @@ pub fn not_signed_in(stderr: &str) -> bool {stderr.contains("Not signed in")}+/// Longest piece of grok's stderr quoted in a notice.+const NOTICE_TAIL_CHARS: usize = 600;++/// What a grok run that produced no reply left behind, for [`empty_reply_notice`].+#[derive(Debug, Default)]+pub struct EmptyRun<'a> {+ pub stderr: &'a str,+ /// grok's `error` events.+ pub errors: &'a [String],+ pub stop_reason: Option<&'a str>,+ /// `None` when grok was killed by a signal or its status is unknown.+ pub exit_code: Option<i32>,+}++/// Tools grok refused in headless mode: `permission required: <tool> was not run, …`.+fn refused_tools(stderr: &str) -> Vec<String> {+ let mut tools: Vec<String> = Vec::new();+ for line in stderr.lines() {+ let Some(rest) = line+ .split_once("permission required:")+ .map(|(_, r)| r.trim())+ else {+ continue;+ };+ let tool = rest+ .split_once(" was not run")+ .map_or(rest, |(t, _)| t)+ .trim()+ .to_string();+ if !tool.is_empty() && !tools.contains(&tool) {+ tools.push(tool);+ }+ }+ tools+}++/// The message shown instead of an empty reply: why grok gave none, with any quoted output+/// redacted (`secrets`: the gateway token and the kwant's server secrets) and shortened.+pub fn empty_reply_notice(run: &EmptyRun<'_>, secrets: &[String]) -> String {+ let quote = |text: &str| {+ let text = crate::mcp::redact(text.trim(), secrets);+ let start = text+ .char_indices()+ .rev()+ .nth(NOTICE_TAIL_CHARS - 1)+ .map_or(0, |(i, _)| i);+ if start > 0 {+ format!("…{}", &text[start..])+ } else {+ text+ }+ };+ let refused = refused_tools(run.stderr);+ if !refused.is_empty() {+ return format!(+ "grok stopped without a reply: it needed approval to run {}, and a headless grok run can't ask for it. kwnt only approves MCP tools assigned to this kwant (through its approval card), not grok's own tools.",+ refused.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(", ")+ );+ }+ if not_signed_in(run.stderr) {+ return "grok isn't signed in on this computer. Run `grok login` (or `grok login --device-code` without a browser), then try again.".into();+ }+ if let Some(error) = run.errors.first() {+ return format!("grok stopped with an error: {}", quote(error));+ }+ if run.stop_reason == Some("refusal") {+ return "grok declined to answer this request.".into();+ }+ let ended = match (run.exit_code, run.stop_reason) {+ (Some(0), Some(reason)) => {+ format!("grok finished without a reply (stop reason: {reason}).")+ }+ (Some(0), None) => "grok finished without a reply.".to_string(),+ (Some(code), _) => format!("grok exited with code {code} without a reply."),+ (None, _) => "grok was stopped before it replied.".to_string(),+ };+ match run.stderr.trim() {+ "" => ended,+ tail => format!("{ended} Its last output:\n{}", quote(tail)),+ }+}+/// Adds kwnt's gateway as the run's only MCP server. The token is not written: grok expands/// `${VAR}` in headers from its own env, and the shell policy hides that variable from the/// commands grok runs. `slowest` is the longest timeout among the kwant's servers.@@ -339,6 +421,100 @@ allow = ["Bash(*)"]assert!(parser.finish().is_empty());}+ #[test]+ fn empty_reply_explains_refused_tools() {+ let stderr = "warn: x\npermission required: run_terminal_cmd was not run, as a headless run cannot ask for approval\npermission required: kwnt__alpha-ping was not run, as a headless run cannot ask for approval\npermission required: run_terminal_cmd was not run, as a headless run cannot ask for approval\n";+ let notice = empty_reply_notice(+ &EmptyRun {+ stderr,+ exit_code: Some(0),+ ..Default::default()+ },+ &[],+ );+ assert!(+ notice.contains("needed approval to run `run_terminal_cmd`, `kwnt__alpha-ping`,"),+ "{notice}"+ );+ }++ #[test]+ fn empty_reply_explains_why_and_hides_secrets() {+ let secrets = ["gw-token-123".to_string(), "sk-server".to_string()];+ let notice = |run: EmptyRun<'_>| empty_reply_notice(&run, &secrets);++ let login = notice(EmptyRun {+ stderr:+ "Not signed in. To authenticate without a browser, run: grok login --device-code",+ exit_code: Some(1),+ ..Default::default()+ });+ assert!(+ login.contains("isn't signed in") && login.contains("grok login"),+ "{login}"+ );++ let errors = ["upstream said Bearer gw-token-123 is bad".to_string()];+ let error = notice(EmptyRun {+ errors: &errors,+ exit_code: Some(1),+ ..Default::default()+ });+ assert_eq!(+ error,+ "grok stopped with an error: upstream said Bearer ******** is bad"+ );++ let refusal = notice(EmptyRun {+ stop_reason: Some("refusal"),+ exit_code: Some(0),+ ..Default::default()+ });+ assert_eq!(refusal, "grok declined to answer this request.");++ assert_eq!(+ notice(EmptyRun {+ exit_code: Some(0),+ ..Default::default()+ }),+ "grok finished without a reply."+ );+ assert_eq!(+ notice(EmptyRun {+ stop_reason: Some("max_turn_requests"),+ exit_code: Some(0),+ ..Default::default()+ }),+ "grok finished without a reply (stop reason: max_turn_requests)."+ );+ assert_eq!(+ notice(EmptyRun {+ exit_code: None,+ ..Default::default()+ }),+ "grok was stopped before it replied."+ );++ let crash = notice(EmptyRun {+ stderr: "panic: key sk-server leaked\n",+ exit_code: Some(101),+ ..Default::default()+ });+ assert_eq!(crash, "grok exited with code 101 without a reply. Its last output:\npanic: key ******** leaked");++ let long = format!("{}END", "x".repeat(5000));+ let tail = notice(EmptyRun {+ stderr: &long,+ exit_code: Some(2),+ ..Default::default()+ });+ assert!(+ tail.ends_with("xxEND") && tail.contains('…') && tail.chars().count() < 700,+ "{}",+ tail.len()+ );+ }+#[test]fn keeps_only_model_settings() {let kept = model_settings(USER_CONFIG);diff --git a/tests/grok_driver_test.rs b/tests/grok_driver_test.rsindex 129620e6..ccfefd7d 100644--- a/tests/grok_driver_test.rs+++ b/tests/grok_driver_test.rs@@ -370,3 +370,26 @@ async fn grok_reply_comes_from_streaming_json_text_events() {let (reply, _) = grok.run(None).await;assert_eq!(reply, "Hello ✓");}++#[tokio::test]+async fn grok_refusing_a_tool_explains_instead_of_replying_empty() {+ let grok = FakeGrok::new(+ r#"echo 'permission required: run_terminal_cmd was not run, as a headless run cannot ask for approval' >&2; printf '%s\n' '{"type":"end","stopReason":"end_turn"}'"#,+ );+ let (reply, _) = grok.run(None).await;+ assert!(+ reply.contains("needed approval to run `run_terminal_cmd`"),+ "{reply}"+ );+}++#[tokio::test]+async fn grok_crashing_without_output_reports_its_exit_and_hides_the_token() {+ let grok = FakeGrok::new(r#"echo "boom: Bearer $KWNT_MCP_GATEWAY_TOKEN" >&2; exit 3"#);+ let (reply, _) = grok.run(Some(mcp_ctx(grok.dir.path()))).await;+ assert!(+ reply.contains("exited with code 3") && reply.contains("boom"),+ "{reply}"+ );+ assert!(!reply.contains("gw-secret-token"), "{reply}");+}