Skip to main content

orch/engine/runner/agents/
grok.rs

1//! Grok agent runner.
2//!
3//! Headless Grok (`grok -p`) does not read the prompt from stdin. The task
4//! message is `--prompt-file`. The system prompt is passed with
5//! `--system-prompt-override`. Output is `streaming-messages-json`, the
6//! Messages API NDJSON shape, so parsing delegates to the Claude runner.
7//!
8//! ```bash
9//! grok --no-plan --no-wait-for-background \
10//!   --output-format streaming-messages-json \
11//!   --permission-mode bypassPermissions \
12//!   --sandbox off \
13//!   --deny 'Bash(rm *)' \
14//!   --system-prompt-override "$(cat "{sys_file}")" \
15//!   --prompt-file "{msg_file}"
16//! ```
17//!
18//! `--sandbox workspace` only writes the cwd. A worktree's git dir lives
19//! outside that cwd, and the CLI has no extra-dir flag, so task runs use
20//! `--sandbox off`. Orch still isolates the agent in the worktree and denies
21//! `rm` and `git push`. Control sessions (`deny_read_only`) use `read-only`.
22
23use std::iter;
24use std::time::Duration;
25
26use tokio::process::Command;
27
28use super::claude::{self, ClaudeRunner};
29use super::{
30    AgentError, AgentRunner, ParsedResponse, PermissionRules, StreamEvent, shell_single_quote,
31};
32
33/// Grok waits this long for background tools when no timeout flag is passed
34const GROK_BACKGROUND_WAIT_SECS: u64 = 600;
35
36/// Runner for the `grok` CLI
37#[derive(Debug)]
38pub struct GrokRunner;
39
40impl GrokRunner {
41    fn parser() -> ClaudeRunner {
42        ClaudeRunner::new("grok")
43    }
44}
45
46impl AgentRunner for GrokRunner {
47    #[cfg(test)]
48    fn name(&self) -> &'static str {
49        "grok"
50    }
51
52    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent> {
53        claude::stream_events(event)
54    }
55
56    fn router_transcript(&self) -> super::RouterTranscript {
57        super::RouterTranscript::Messages
58    }
59
60    fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
61        Self::parser().extract_text(raw)
62    }
63
64    fn build_command(
65        &self,
66        model: Option<&str>,
67        timeout_cmd: &str,
68        sys_file: &str,
69        msg_file: &str,
70        permissions: &PermissionRules,
71    ) -> String {
72        let sq_sys = shell_single_quote(sys_file);
73        let sq_msg = shell_single_quote(msg_file);
74        let mut args = Vec::new();
75        if !timeout_cmd.is_empty() {
76            args.push(timeout_cmd.to_string());
77        }
78        args.push("grok".to_string());
79        args.push("--no-plan".to_string());
80        // Leftover background tool calls wait 600s, then grok exits 1 and the task blocks
81        args.push("--no-wait-for-background".to_string());
82        args.push("--output-format".to_string());
83        args.push("streaming-messages-json".to_string());
84        args.push("--permission-mode".to_string());
85        args.push(permission_mode(permissions).to_string());
86        args.push("--sandbox".to_string());
87        args.push(sandbox_profile(permissions).to_string());
88        if let Some(model) = model.filter(|m| !m.is_empty()) {
89            args.push("--model".to_string());
90            args.push(shell_single_quote(model));
91        }
92        args.extend(permission_args(permissions));
93        args.push("--system-prompt-override".to_string());
94        args.push(format!("\"$(cat {sq_sys})\""));
95        args.push("--prompt-file".to_string());
96        args.push(sq_msg);
97        args.join(" ")
98    }
99
100    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError> {
101        Self::parser().parse_response(raw)
102    }
103
104    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError {
105        let extracted = startup_errors(stdout);
106        for message in extracted
107            .iter()
108            .map(String::as_str)
109            .chain(iter::once(stdout))
110            .chain(iter::once(stderr))
111        {
112            if let Some(err) = classify_grok_message(message) {
113                return err;
114            }
115        }
116        let stderr = if extracted.is_empty() {
117            stderr.to_string()
118        } else {
119            format!("{stderr}\n{}", extracted.join("\n"))
120        };
121        Self::parser().classify_error(exit_code, stdout, &stderr)
122    }
123
124    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command> {
125        // Classification only needs a JSON answer. One leftover tool call
126        // spends `--max-turns 1` and grok exits with max turns reached
127        let mut cmd = Command::new("grok");
128        cmd.arg("--no-plan")
129            .arg("--no-subagents")
130            .arg("--disable-web-search")
131            .arg("--max-turns")
132            .arg("1")
133            .arg("--output-format")
134            .arg("streaming-messages-json")
135            .arg("--permission-mode")
136            .arg("dontAsk")
137            .arg("--disallowed-tools")
138            .arg(ROUTER_DISALLOWED_TOOLS);
139        if let Some(model) = model.filter(|m| !m.is_empty()) {
140            cmd.arg("--model").arg(model);
141        }
142        cmd.arg("-p").arg(prompt);
143        Ok(cmd)
144    }
145}
146
147/// `streaming-messages-json` result, plus Grok's cost and stop reason
148pub fn find_grok_result(ndjson: &str) -> Option<super::AgentResult> {
149    let mut result = claude::find_claude_result(ndjson)?;
150    let Some((line, _)) = claude::find_ndjson_result_line(ndjson.trim()) else {
151        return Some(result);
152    };
153    let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
154        return Some(result);
155    };
156    if result.cost_usd.is_none() {
157        result.cost_usd = val
158            .get("total_cost_usd")
159            .and_then(serde_json::Value::as_f64);
160    }
161    if val.get("stop_reason").and_then(|v| v.as_str()) == Some("max_tokens") {
162        result.truncated_by_length = true;
163    }
164    Some(result)
165}
166
167fn permission_mode(permissions: &PermissionRules) -> &'static str {
168    if permissions.autonomous {
169        "bypassPermissions"
170    } else if permissions.deny_read_only {
171        "dontAsk"
172    } else {
173        "acceptEdits"
174    }
175}
176
177fn sandbox_profile(permissions: &PermissionRules) -> &'static str {
178    if permissions.deny_read_only {
179        "read-only"
180    } else {
181        "off"
182    }
183}
184
185/// Tools the grok router must not expose. One tool call spends `--max-turns 1`
186const ROUTER_DISALLOWED_TOOLS: &str = concat!(
187    "read_file,grep,list_dir,search_replace,write,run_terminal_cmd,",
188    "web_search,web_fetch,task,todo_write,monitor,search_tool,use_tool,",
189    "workflow,enter_plan_mode,exit_plan_mode,ask_user_question,",
190    "send_feedback,image_gen,image_edit,image_to_video,reference_to_video"
191);
192
193/// Claude tool names that map to a Grok tool id for `--tools` / `--disallowed-tools`
194fn grok_tool_id(name: &str) -> Option<&'static str> {
195    Some(match name {
196        "Read" => "read_file",
197        "Grep" => "grep",
198        "Glob" => "list_dir",
199        "Edit" => "search_replace",
200        "Write" => "write",
201        "Bash" => "run_terminal_cmd",
202        "WebFetch" => "web_fetch",
203        "WebSearch" => "web_search",
204        "Task" => "task",
205        "TodoWrite" => "todo_write",
206        _ => return None,
207    })
208}
209
210fn permission_args(permissions: &PermissionRules) -> Vec<String> {
211    if !permissions.allowed_tools.is_empty() {
212        return allow_args(permissions);
213    }
214    deny_args(&permissions.disallowed_tools)
215}
216
217fn allow_args(permissions: &PermissionRules) -> Vec<String> {
218    let mut tools = Vec::new();
219    let mut allows = Vec::new();
220    for item in &permissions.allowed_tools {
221        if let Some(id) = grok_tool_id(item) {
222            if !tools.contains(&id) {
223                tools.push(id);
224            }
225            if (item == "Edit" || item == "Write") && !permissions.allowed_edit_paths.is_empty() {
226                for path in &permissions.allowed_edit_paths {
227                    allows.push(format!("{item}({}/**)", path.display()));
228                }
229            }
230        } else if item.chars().next().is_some_and(|c| c.is_ascii_lowercase()) {
231            // CLI command names become shell allow rules. PascalCase leftovers
232            // such as Skill are Claude-only tools, not shell commands
233            allows.push(format!("Bash({item} *)"));
234        }
235    }
236    // An allowlist does not express the rm / git-push bans. Keep those denies.
237    let mut args = Vec::new();
238    if !tools.is_empty() {
239        args.push("--tools".to_string());
240        args.push(shell_single_quote(&tools.join(",")));
241    }
242    for rule in allows {
243        args.push("--allow".to_string());
244        args.push(shell_single_quote(&rule));
245    }
246    args.extend(deny_args(&permissions.disallowed_tools));
247    args
248}
249
250fn deny_args(rules: &[String]) -> Vec<String> {
251    let mut remove = Vec::new();
252    let mut denies = Vec::new();
253    for rule in rules {
254        match rule.as_str() {
255            "Read" | "Grep" | "Glob" | "Edit" | "Write" | "Bash" => {
256                if let Some(id) = grok_tool_id(rule)
257                    && !remove.contains(&id)
258                {
259                    remove.push(id);
260                }
261            }
262            _ => denies.push(rule.as_str()),
263        }
264    }
265    let mut args = Vec::new();
266    if !remove.is_empty() {
267        args.push("--disallowed-tools".to_string());
268        args.push(shell_single_quote(&remove.join(",")));
269    }
270    for rule in denies {
271        args.push("--deny".to_string());
272        args.push(shell_single_quote(rule));
273    }
274    args
275}
276
277/// `type:error` messages. These are startup failures, not assistant prose.
278fn startup_errors(stdout: &str) -> Vec<String> {
279    let mut out = Vec::new();
280    for line in stdout.lines() {
281        let line = line.trim();
282        if line.is_empty() {
283            continue;
284        }
285        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
286            continue;
287        };
288        if val.get("type").and_then(|t| t.as_str()) != Some("error") {
289            continue;
290        }
291        if let Some(message) = val.get("message").and_then(|m| m.as_str())
292            && !message.is_empty()
293        {
294            out.push(message.to_string());
295        }
296    }
297    out
298}
299
300/// Grok phrases the shared classifier does not already name
301fn classify_grok_message(message: &str) -> Option<AgentError> {
302    let lower = message.to_lowercase();
303    if lower.contains("not logged in")
304        || lower.contains("please log in")
305        || lower.contains("grok login")
306        || lower.contains("xai_api_key")
307        || lower.contains("authentication failed")
308        || lower.contains("could not refresh")
309    {
310        return Some(AgentError::Auth {
311            message: message.to_string(),
312        });
313    }
314    if lower.contains("permission required") {
315        return Some(AgentError::PermissionDenied {
316            message: message.to_string(),
317        });
318    }
319    if lower.contains("the wait for background work ran out") {
320        return Some(AgentError::Timeout {
321            elapsed: Duration::from_secs(GROK_BACKGROUND_WAIT_SECS),
322        });
323    }
324    None
325}
326
327#[cfg(test)]
328mod tests {
329    use std::path::PathBuf;
330
331    use super::*;
332    use crate::engine::runner::agents::SandboxLevel;
333    use crate::engine::runner::parse_session_output;
334    use crate::engine::runner::session::SessionOutput;
335
336    fn runner() -> GrokRunner {
337        GrokRunner
338    }
339
340    fn perms(autonomous: bool, disallowed: &[&str], allowed: &[&str]) -> PermissionRules {
341        PermissionRules {
342            autonomous,
343            sandbox: SandboxLevel::WorkspaceWrite,
344            disallowed_tools: disallowed.iter().map(|s| (*s).to_string()).collect(),
345            allowed_tools: allowed.iter().map(|s| (*s).to_string()).collect(),
346            allowed_edit_paths: vec![],
347            deny_read_only: false,
348            extra_writable_dirs: vec![],
349        }
350    }
351
352    #[test]
353    fn build_command_autonomous_denies_rm_and_passes_files() {
354        let cmd = runner().build_command(
355            Some("fast"),
356            "timeout 1800",
357            "/tmp/sys.txt",
358            "/tmp/msg.txt",
359            &perms(true, &["Bash(rm *)", "Bash(git push*)"], &[]),
360        );
361        assert!(cmd.starts_with("timeout 1800 grok "), "{cmd}");
362        assert!(cmd.contains("--model 'fast'"), "{cmd}");
363        assert!(
364            cmd.contains("--output-format streaming-messages-json"),
365            "{cmd}"
366        );
367        assert!(cmd.contains("--permission-mode bypassPermissions"), "{cmd}");
368        assert!(cmd.contains("--sandbox off"), "{cmd}");
369        assert!(cmd.contains("--no-plan"), "{cmd}");
370        assert!(cmd.contains("--no-wait-for-background"), "{cmd}");
371        assert!(cmd.contains("--deny 'Bash(rm *)'"), "{cmd}");
372        assert!(cmd.contains("--deny 'Bash(git push*)'"), "{cmd}");
373        assert!(cmd.contains("--prompt-file '/tmp/msg.txt'"), "{cmd}");
374        assert!(
375            cmd.contains("--system-prompt-override \"$(cat '/tmp/sys.txt')\""),
376            "{cmd}"
377        );
378        assert!(!cmd.contains("< "), "{cmd}");
379    }
380
381    #[test]
382    fn build_command_omits_empty_model() {
383        let cmd = runner().build_command(
384            Some(""),
385            "",
386            "/tmp/sys.txt",
387            "/tmp/msg.txt",
388            &perms(true, &[], &[]),
389        );
390        assert!(!cmd.contains("--model"), "{cmd}");
391    }
392
393    #[test]
394    fn build_command_supervised_accepts_edits() {
395        let cmd = runner().build_command(
396            None,
397            "",
398            "/tmp/sys.txt",
399            "/tmp/msg.txt",
400            &perms(false, &[], &[]),
401        );
402        assert!(cmd.contains("--permission-mode acceptEdits"), "{cmd}");
403    }
404
405    #[test]
406    fn build_command_read_only_removes_read_tools() {
407        let rules = PermissionRules::deny_read_only();
408        let cmd = runner().build_command(None, "", "/tmp/sys.txt", "/tmp/msg.txt", &rules);
409        assert!(cmd.contains("--sandbox read-only"), "{cmd}");
410        assert!(cmd.contains("--permission-mode bypassPermissions"), "{cmd}");
411        assert!(cmd.contains("read_file"), "{cmd}");
412        assert!(cmd.contains("grep"), "{cmd}");
413        assert!(cmd.contains("list_dir"), "{cmd}");
414        assert!(cmd.contains("--deny 'Bash(cat *)'"), "{cmd}");
415    }
416
417    #[test]
418    fn build_command_allowlist_keeps_destructive_denies() {
419        let mut rules = perms(true, &["Bash(rm *)"], &["Edit", "Write", "Bash", "git"]);
420        rules.allowed_edit_paths = vec![PathBuf::from("/work/tree")];
421        let cmd = runner().build_command(None, "", "/tmp/sys.txt", "/tmp/msg.txt", &rules);
422        assert!(
423            cmd.contains("--tools 'search_replace,write,run_terminal_cmd'"),
424            "{cmd}"
425        );
426        assert!(cmd.contains("--allow 'Edit(/work/tree/**)'"), "{cmd}");
427        assert!(cmd.contains("--allow 'Write(/work/tree/**)'"), "{cmd}");
428        assert!(cmd.contains("--allow 'Bash(git *)'"), "{cmd}");
429        assert!(cmd.contains("--deny 'Bash(rm *)'"), "{cmd}");
430    }
431
432    #[test]
433    fn parse_response_reads_messages_result() {
434        let raw = concat!(
435            r#"{"type":"system","subtype":"init","model":"test"}"#,
436            "\n",
437            r#"{"type":"result","subtype":"success","is_error":false,"result":"{\"status\":\"done\",\"summary\":\"shipped\",\"accomplished\":[\"a\"],\"remaining\":[],\"files\":[]}","usage":{"input_tokens":8,"output_tokens":3},"total_cost_usd":0.02,"duration_ms":40,"stop_reason":"end_turn"}"#,
438            "\n",
439        );
440        let parsed = runner().parse_response(raw).expect("parse");
441        assert_eq!(parsed.response.status, "done");
442        assert_eq!(parsed.response.summary, "shipped");
443        assert_eq!(parsed.input_tokens, Some(8));
444        assert_eq!(parsed.output_tokens, Some(3));
445    }
446
447    #[test]
448    fn find_result_reads_cost_and_max_tokens() {
449        let raw = r#"{"type":"result","subtype":"success","is_error":false,"result":"partial","usage":{"input_tokens":1,"output_tokens":2},"total_cost_usd":1.5,"stop_reason":"max_tokens"}"#;
450        let result = find_grok_result(raw).expect("result");
451        assert_eq!(result.result_text, "partial");
452        assert_eq!(result.cost_usd, Some(1.5));
453        assert!(result.truncated_by_length);
454        assert_eq!(result.input_tokens, Some(1));
455    }
456
457    #[test]
458    fn classify_error_rate_limit_from_error_event() {
459        let stdout = r#"{"type":"error","message":"429 Too Many Requests"}"#;
460        let err = runner().classify_error(1, stdout, "");
461        assert!(matches!(err, AgentError::RateLimit { .. }), "{err}");
462    }
463
464    #[test]
465    fn classify_error_model_unavailable() {
466        let stdout = r#"{"type":"error","message":"The model `missing` is not supported"}"#;
467        let err = runner().classify_error(1, stdout, "");
468        match err {
469            AgentError::ModelUnavailable { model, .. } => assert_eq!(model, "missing"),
470            other => panic!("expected model unavailable, got {other}"),
471        }
472    }
473
474    #[test]
475    fn classify_error_login_is_auth() {
476        let stdout = r#"{"type":"error","message":"Not logged in. Run grok login."}"#;
477        let err = runner().classify_error(1, stdout, "");
478        assert!(matches!(err, AgentError::Auth { .. }), "{err}");
479    }
480
481    #[test]
482    fn classify_error_permission_required() {
483        let stdout =
484            r#"{"type":"error","message":"permission required: Edit calc.py was not run"}"#;
485        let err = runner().classify_error(1, stdout, "");
486        assert!(matches!(err, AgentError::PermissionDenied { .. }), "{err}");
487    }
488
489    #[test]
490    fn router_command_disallows_leftover_tools() {
491        let cmd = runner()
492            .router_command("classify this task", None)
493            .expect("router command");
494        let args: Vec<String> = cmd
495            .as_std()
496            .get_args()
497            .map(|a| a.to_string_lossy().into_owned())
498            .collect();
499        let disallowed = args
500            .windows(2)
501            .find(|pair| pair[0] == "--disallowed-tools")
502            .map(|pair| pair[1].as_str())
503            .expect("disallowed-tools flag");
504        for tool in ["search_tool", "use_tool", "todo_write", "workflow"] {
505            assert!(
506                disallowed.split(',').any(|name| name == tool),
507                "{tool} missing from {disallowed}"
508            );
509        }
510    }
511
512    #[test]
513    fn classify_error_background_wait_expiry_is_timeout() {
514        let stdout = r#"{"type":"error","message":"the wait for background work ran out after 600 s and exit stopped 1 background task. Pass --background-wait-timeout <secs> to wait longer, or --no-wait-for-background to exit as soon as the prompt's turn ends"}"#;
515        let err = runner().classify_error(1, stdout, "");
516        assert!(matches!(err, AgentError::Timeout { .. }), "{err}");
517    }
518
519    #[test]
520    fn parse_session_output_background_wait_envelope_is_timeout() {
521        let ndjson = r#"{"type":"result","subtype":"error_during_execution","is_error":true,"num_turns":12,"errors":["the wait for background work ran out after 600 s and exit stopped 1 background task. Pass --background-wait-timeout <secs> to wait longer, or --no-wait-for-background to exit as soon as the prompt's turn ends"],"costUSD":2.01,"usage":{"input_tokens":100,"output_tokens":50}}"#;
522        let session = SessionOutput {
523            exit_code: 1,
524            raw_stdout: ndjson.to_string(),
525            raw_stderr: String::new(),
526            elapsed_secs: Some(1313),
527            sandbox_error: None,
528        };
529        let err = parse_session_output("489522", "grok", &runner(), &session)
530            .expect_err("background-wait expiry should be an error");
531        match err {
532            AgentError::Timeout { elapsed } => {
533                assert_eq!(elapsed, Duration::from_secs(1313));
534            }
535            other => panic!("expected Timeout, got {other}"),
536        }
537    }
538}